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

MethodDescription
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

APIUse
Readable.toWeb(nodeReadable)Node → Web
Writable.toWeb(nodeWritable)Node → Web

6. Converting Web Streams to Node.js Streams

APIUse
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

SourceMechanism
controller.desiredSizeHint when to enqueue more
pull() callbackCalled when consumer ready
Strategynew ByteLengthQueuingStrategy({ highWaterMark })

9. Understanding Web Streams vs Node Streams

AspectWebNode
StandardWHATWGNode-specific
PortabilityBrowser + NodeNode only
API stylePromise-basedEventEmitter
PerformanceSlightly slowerOptimized

10. Using Async Iteration with Web Streams

NoteDetail
ReadableStream is async-iterablefor await (const chunk of stream) v18.7+
Cancel via breakCalls stream.cancel()