-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
read-stream.ts
47 lines (44 loc) · 1.44 KB
/
read-stream.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
type Readable = {
readonly on: {
(event: 'data', handler: (chunk: unknown) => void): void;
(event: 'end', handler: () => void): void;
(event: 'error', handler: (error: unknown) => void): void;
};
};
type ReadStream = {
/**
* Capture all data from a readable stream to a `Buffer`.
*/
(readable: Readable): Promise<Buffer>;
/**
* Capture all data from a readable stream to a `string` according to the given `encoding`.
*/
(readable: Readable, encoding: BufferEncoding): Promise<string>;
/**
* Capture all data from a readable stream to a `Buffer`.
*/
(readable: Readable, encoding?: BufferEncoding | undefined): Promise<Buffer | string>;
};
/**
* Capture all data from a readable stream to a `Buffer` or `string` (if an `encoding` is set).
*/
const readStream = ((readable, encoding) => {
return new Promise<Buffer | string>((resolve, reject) => {
const buffers: Buffer[] = [];
readable.on('data', (chunk) => {
if (chunk instanceof Buffer) {
buffers.push(chunk);
} else if (typeof chunk === 'string') {
buffers.push(Buffer.from(chunk));
} else {
reject(new Error('Object mode streams are not supported'));
}
});
readable.on('error', (error) => reject(error));
readable.on('end', () => {
const buffer = Buffer.concat(buffers);
resolve(encoding != null ? buffer.toString(encoding) : buffer);
});
});
}) as ReadStream;
export { readStream };