-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node.ts
33 lines (26 loc) 路 740 Bytes
/
node.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
import type { ServerResponse } from 'http';
import type { Options } from 'piecemeal';
import { generate } from 'piecemeal';
export function stream<T extends any>(
data: AsyncIterableIterator<T> | IterableIterator<T>,
options: Options = {},
) {
const boundary = options.boundary || '-';
async function pipe(res: ServerResponse) {
res.setHeader('connection', 'keep-alive');
res.setHeader('content-type', `multipart/mixed;boundary="${boundary}"`);
res.setHeader('transfer-encoding', 'chunked');
res.flushHeaders();
let ended = false;
res.once('close', () => (ended = true));
await generate(data, boundary, res.write.bind(res), {
get aborted() {
return ended;
},
});
res.end();
}
return {
pipe,
};
}