54 lines
1.2 KiB
JavaScript
Raw Normal View History

'use strict';
2022-08-08 15:50:34 +02:00
/**
* Utils file containing file treatment utils
*/
const { Writable } = require('stream');
2022-08-08 23:33:39 +02:00
const bytesToKbytes = (bytes) => Math.round((bytes / 1000) * 100) / 100;
2022-09-13 10:21:30 +02:00
const kbytesToBytes = (kbytes) => kbytes * 1000;
2022-08-08 23:33:39 +02:00
const streamToBuffer = (stream) =>
new Promise((resolve, reject) => {
const chunks = [];
2022-08-08 23:33:39 +02:00
stream.on('data', (chunk) => {
chunks.push(chunk);
});
stream.on('end', () => {
resolve(Buffer.concat(chunks));
});
stream.on('error', reject);
});
2022-08-08 23:33:39 +02:00
const getStreamSize = (stream) =>
new Promise((resolve, reject) => {
let size = 0;
2022-08-08 23:33:39 +02:00
stream.on('data', (chunk) => {
size += Buffer.byteLength(chunk);
});
stream.on('close', () => resolve(size));
stream.on('error', reject);
stream.resume();
});
/**
* Create a writeable Node.js stream that discards received data.
* Useful for testing, draining a stream of data, etc.
*/
2022-08-04 12:58:47 +02:00
function writableDiscardStream(options) {
return new Writable({
...options,
write(chunk, encding, callback) {
setImmediate(callback);
},
});
}
module.exports = {
streamToBuffer,
bytesToKbytes,
2022-09-13 10:21:30 +02:00
kbytesToBytes,
getStreamSize,
2022-08-04 13:05:25 +02:00
writableDiscardStream,
};