-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
collect.ts
36 lines (36 loc) · 871 Bytes
/
collect.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
/**
* Reads all chunks from a readable stream and returns them as an array of chunks.
*
* ```ts
* import { collect } from "@core/streamutil/collect";
*
* const reader = new ReadableStream<number>({
* start(controller) {
* controller.enqueue(1);
* controller.enqueue(2);
* controller.enqueue(3);
* controller.close();
* },
* });
*
* console.log(await collect(reader)); // [1, 2, 3]
* ```
*
* @param stream The readable stream to read chunks from.
* @returns A promise that resolves with an array of all the chunks read from the stream.
*/
export async function collect<T>(
stream: ReadableStream<T>,
options: StreamPipeOptions = {},
): Promise<T[]> {
const chunks: T[] = [];
await stream.pipeTo(
new WritableStream({
write(chunk) {
chunks.push(chunk);
},
}),
options,
);
return chunks;
}