2020-03-06 18:41:48 +01:00
|
|
|
/**
|
|
|
|
* Utils file containing file treatment utils
|
|
|
|
*/
|
2023-04-28 18:20:31 +02:00
|
|
|
import { Readable, Writable, WritableOptions } from 'node:stream';
|
2020-03-06 18:41:48 +01:00
|
|
|
|
2023-04-28 18:20:31 +02:00
|
|
|
const kbytesToBytes = (kbytes: number) => kbytes * 1000;
|
|
|
|
const bytesToKbytes = (bytes: number) => Math.round((bytes / 1000) * 100) / 100;
|
|
|
|
const bytesToHumanReadable = (bytes: number) => {
|
2022-09-23 14:44:20 +02:00
|
|
|
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];
|
|
|
|
if (bytes === 0) return '0 Bytes';
|
2023-04-28 18:20:31 +02:00
|
|
|
const i = parseInt(`${Math.floor(Math.log(bytes) / Math.log(1000))}`, 10);
|
|
|
|
return `${Math.round(bytes / 1000 ** i)} ${sizes[i]}`;
|
2022-09-23 14:44:20 +02:00
|
|
|
};
|
2020-03-06 18:41:48 +01:00
|
|
|
|
2023-04-28 18:20:31 +02:00
|
|
|
const streamToBuffer = (stream: Readable) =>
|
2020-03-08 18:43:50 +01:00
|
|
|
new Promise((resolve, reject) => {
|
2023-04-28 18:20:31 +02:00
|
|
|
const chunks: Uint8Array[] = [];
|
2022-08-08 23:33:39 +02:00
|
|
|
stream.on('data', (chunk) => {
|
2020-03-08 18:43:50 +01:00
|
|
|
chunks.push(chunk);
|
|
|
|
});
|
|
|
|
stream.on('end', () => {
|
|
|
|
resolve(Buffer.concat(chunks));
|
|
|
|
});
|
|
|
|
stream.on('error', reject);
|
|
|
|
});
|
|
|
|
|
2023-04-28 18:20:31 +02:00
|
|
|
const getStreamSize = (stream: Readable) =>
|
2022-01-05 17:36:21 +01:00
|
|
|
new Promise((resolve, reject) => {
|
|
|
|
let size = 0;
|
2022-08-08 23:33:39 +02:00
|
|
|
stream.on('data', (chunk) => {
|
|
|
|
size += Buffer.byteLength(chunk);
|
|
|
|
});
|
2022-01-05 17:36:21 +01:00
|
|
|
stream.on('close', () => resolve(size));
|
|
|
|
stream.on('error', reject);
|
|
|
|
stream.resume();
|
|
|
|
});
|
|
|
|
|
2022-08-04 12:56:58 +02:00
|
|
|
/**
|
|
|
|
* Create a writeable Node.js stream that discards received data.
|
|
|
|
* Useful for testing, draining a stream of data, etc.
|
|
|
|
*/
|
2023-04-28 18:20:31 +02:00
|
|
|
function writableDiscardStream(options: WritableOptions) {
|
2022-08-04 12:56:58 +02:00
|
|
|
return new Writable({
|
|
|
|
...options,
|
|
|
|
write(chunk, encding, callback) {
|
|
|
|
setImmediate(callback);
|
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2023-04-27 23:18:48 +02:00
|
|
|
export {
|
2020-03-08 18:43:50 +01:00
|
|
|
streamToBuffer,
|
2022-09-23 14:44:20 +02:00
|
|
|
bytesToHumanReadable,
|
2020-03-06 18:41:48 +01:00
|
|
|
bytesToKbytes,
|
2022-09-13 10:21:30 +02:00
|
|
|
kbytesToBytes,
|
2022-01-05 17:36:21 +01:00
|
|
|
getStreamSize,
|
2022-08-04 13:05:25 +02:00
|
|
|
writableDiscardStream,
|
2020-03-06 18:41:48 +01:00
|
|
|
};
|