1 |
|
2 |
|
3 | import {Readable} from 'stream';
|
4 | import type {Blob} from '@parcel/types';
|
5 |
|
6 | export async function measureStreamLength(stream: Readable): Promise<number> {
|
7 | return new Promise((resolve, reject) => {
|
8 | let length = 0;
|
9 | stream.on('data', chunk => {
|
10 | length += chunk;
|
11 | });
|
12 | stream.on('end', () => resolve(length));
|
13 | stream.on('error', reject);
|
14 | });
|
15 | }
|
16 |
|
17 | export function readableFromStringOrBuffer(str: string | Buffer): Readable {
|
18 |
|
19 | const stream = new Readable();
|
20 | stream.push(str);
|
21 | stream.push(null);
|
22 | return stream;
|
23 | }
|
24 |
|
25 | export async function bufferStream(stream: Readable): Promise<Buffer> {
|
26 | return new Promise((resolve, reject) => {
|
27 | let buf = Buffer.from([]);
|
28 | stream.on('data', data => {
|
29 | buf = Buffer.concat([buf, data]);
|
30 | });
|
31 | stream.on('end', () => {
|
32 | resolve(buf);
|
33 | });
|
34 | stream.on('error', reject);
|
35 | });
|
36 | }
|
37 |
|
38 | export function blobToStream(blob: Blob): Readable {
|
39 | if (blob instanceof Readable) {
|
40 | return blob;
|
41 | }
|
42 |
|
43 | return readableFromStringOrBuffer(blob);
|
44 | }
|