Using Web Streams API
1. Creating ReadableStream
Example
const rs = new ReadableStream({
start(controller) {
controller.enqueue("hello");
controller.enqueue("world");
controller.close();
}
});
2. Creating WritableStream
Example
const ws = new WritableStream({
write(chunk) { console.log("got", chunk); },
close() { console.log("done"); }
});
3. Using TransformStream
| Method | Description |
|---|---|
start(controller) | Init |
transform(chunk, controller) | Process each chunk |
flush(controller) | Final cleanup |
4. Piping Web Streams
Example
await readable.pipeThrough(new TextDecoderStream())
.pipeThrough(new MyTransform())
.pipeTo(writable);
5. Converting Node.js Streams to Web Streams
| API | Use |
|---|---|
Readable.toWeb(nodeReadable) | Node → Web |
Writable.toWeb(nodeWritable) | Node → Web |
6. Converting Web Streams to Node.js Streams
| API | Use |
|---|---|
Readable.fromWeb(webReadable) | Web → Node |
Writable.fromWeb(webWritable) | Web → Node |
7. Using Streams with Fetch API
Example: Stream response
const res = await fetch(url);
for await (const chunk of res.body) process(chunk); // ReadableStream is async-iterable
8. Handling Backpressure in Web Streams
| Source | Mechanism |
|---|---|
controller.desiredSize | Hint when to enqueue more |
pull() callback | Called when consumer ready |
| Strategy | new ByteLengthQueuingStrategy({ highWaterMark }) |
9. Understanding Web Streams vs Node Streams
| Aspect | Web | Node |
|---|---|---|
| Standard | WHATWG | Node-specific |
| Portability | Browser + Node | Node only |
| API style | Promise-based | EventEmitter |
| Performance | Slightly slower | Optimized |
10. Using Async Iteration with Web Streams
| Note | Detail |
|---|---|
| ReadableStream is async-iterable | for await (const chunk of stream) v18.7+ |
Cancel via break | Calls stream.cancel() |