-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstreamConverters.js
More file actions
37 lines (36 loc) · 1.06 KB
/
streamConverters.js
File metadata and controls
37 lines (36 loc) · 1.06 KB
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
/**
* Pipe a web ReadableStream to a node Writable.
* @typedef {import('stream').Writable} Writable
* @param {ReadableStream} input
* @param {Writable} output
* @returns {Promise<void>}
*/
export async function pipe(input, output) {
// TODO: typescript hates for-await? should just be:
// for await (const chunk of input) {}
const reader = input.getReader()
while (true) {
const { done, value } = await reader.read()
if (done) break
output.write(value)
}
output.end()
}
/**
* Convert a node fs ReadStream to a web ReadableStream.
* @typedef {import('fs').ReadStream} ReadStream
* @param {ReadStream} fsStream
* @returns {ReadableStream}
*/
export function readStreamToReadableStream(fsStream) {
return new ReadableStream({
start(/** @type {ReadableStreamDefaultController} */ controller) {
fsStream.on('data', (chunk) => { controller.enqueue(chunk) })
fsStream.on('end', () => { controller.close() })
fsStream.on('error', (error) => { controller.error(error) })
},
cancel() {
fsStream.destroy()
},
})
}