Skip to content
File

Blob: samples/nodejs-compat-streams-split2/worker.js

javascript32 lines
1import {
2 PassThrough,
3 Transform,
4 Readable,
5} from 'node:stream';
6 
7import { default as split2 } from 'split2';
8 
9const enc = new TextEncoder();
10 
11export default {
12 async fetch() {
13 const pt = new PassThrough();
14 
15 // split2 will remove the new lines from the single input stream,
16 // pushing each individual line as a separate chunk. We use this
17 // transform to add the new lines back in just to show the effect
18 // in the output.
19 const lb = new Transform({
20 transform(chunk, encoding, callback) {
21 callback(null, enc.encode(chunk + '\n'));
22 }
23 });
24 
25 const readable = pt.pipe(split2()).pipe(lb);
26 
27 pt.end('hello\nfrom\nthe\nwonderful\nworld\nof\nnode.js\nstreams!');
28 
29 return new Response(Readable.toWeb(readable));
30 }
31};