UNPKG

1.71 kBJavaScriptView Raw
1// @flow strict-local
2
3import {Readable, PassThrough} from 'stream';
4import type {Blob} from '@parcel/types';
5
6export 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
17export function readableFromStringOrBuffer(str: string | Buffer): Readable {
18 // https://stackoverflow.com/questions/12755997/how-to-create-streams-from-string-in-node-js
19 const stream = new Readable();
20 stream.push(str);
21 stream.push(null);
22 return stream;
23}
24
25export 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
38export function blobToStream(blob: Blob): Readable {
39 if (blob instanceof Readable) {
40 return blob;
41 }
42
43 return readableFromStringOrBuffer(blob);
44}
45
46export function streamFromPromise(promise: Promise<Blob>): Readable {
47 const stream = new PassThrough();
48 promise.then(blob => {
49 if (blob instanceof Readable) {
50 blob.pipe(stream);
51 } else {
52 stream.end(blob);
53 }
54 });
55
56 return stream;
57}
58
59export function fallbackStream(
60 stream: Readable,
61 fallback: () => Readable,
62): Readable {
63 const res = new PassThrough();
64 stream.on('error', err => {
65 if (err.code === 'ENOENT') {
66 fallback().pipe(res);
67 } else {
68 res.emit('error', err);
69 }
70 });
71
72 stream.pipe(res);
73 return res;
74}