This repository has been archived by the owner on Jul 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stream.ts
70 lines (63 loc) · 1.95 KB
/
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { from } from 'https://deno.land/std@0.143.0/node/internal/streams/readable.mjs';
// Concatenates several readable streams into one.
export function concatenateReadableStreams(
...streams: Array<ReadableStream>
): ReadableStream {
const { readable, writable } = new TransformStream();
(async () => {
let i = 0;
for (const stream of streams) {
await stream.pipeTo(writable, {
preventClose: true,
});
i = i + 1;
if (i === streams.length) {
await writable.getWriter().close();
}
}
})();
return readable;
}
// Streams a string.
export function streamString(input: string): ReadableStream<string> {
return new ReadableStream({
start(controller) {
controller.enqueue(input);
controller.close();
},
});
}
// Takes two streams, the head and body content and returns a concatenated
// complete HTML stream with the html, head and body tags around them.
export function streamDocument(head: ReadableStream, body: ReadableStream) {
return concatenateReadableStreams(
streamString('<!DOCTYPE html><head>'),
head,
streamString('</head><body>'),
body,
streamString('</body></html>'),
);
}
// Converts a NodeJS.ReadableStream to a Deno.ReadableStream.
export const nodeReadableStreamToWebReadableStream = (
inputStream: NodeJS.ReadableStream,
): ReadableStream => {
const outputStream = new TransformStream();
const outputStreamWritableWriter = outputStream.writable.getWriter();
(async () => {
for await (const chunk of inputStream) {
outputStreamWritableWriter.write(chunk);
}
})().then(() => {
outputStreamWritableWriter.close();
}).catch((error) => {
outputStreamWritableWriter.abort(error);
});
return outputStream.readable;
};
// Converts a Deno.ReadableStream to a NodeJS.ReadableStream.
export const webReadableStreamToNodeReadableStream = (
inputStream: ReadableStream,
): NodeJS.ReadableStream => {
return from(inputStream);
};