Lesson 3 of 9 · 21m
Streams: Moving Data Without Buffering the World
ReadableStream, WritableStream, and TransformStream solve incremental data flow — but only if you respect backpressure and cancellation.
Most developers first meet streams when response.body is not the string they expected. The deeper point is architectural: large data should move through your application in chunks, with the consumer controlling the pace. Buffering everything is fine until somebody uploads a 2 GB log export on hotel Wi-Fi and your tab tries to materialize it three times.
Reading incrementally
const response = await fetch("/exports/events.ndjson");
const reader = response.body.getReader();
const decoder = new TextDecoder();
let partial = "";
while (true) {
const { value, done } = await reader.read();
if (done) break;
partial += decoder.decode(value, { stream: true });
const lines = partial.split("\n");
partial = lines.pop();
for (const line of lines) consumeEvent(JSON.parse(line));
}The important detail is not the loop; it is that memory stays roughly proportional to a chunk plus one partial line. That is why streams matter. They turn huge payloads into a flow problem.
Backpressure is the contract
A writable side signals "slow down" through promises and desired size. If you ignore that signal and write as fast as the producer can generate data, you have rebuilt buffering with extra steps.
const uppercase = new TransformStream({
transform(chunk, controller) {
controller.enqueue(chunk.toUpperCase());
},
});
response.body
.pipeThrough(uppercase)
.pipeTo(writable);pipeThrough and pipeTo are valuable because they propagate backpressure and errors for you. Hand-rolled pump loops often forget one half of the chain: the producer keeps reading after the consumer failed, or cancellation never reaches the network request.
Cancellation is a feature
Users close dialogs, navigate away, and abort uploads. A stream that cannot cancel is a resource leak. AbortSignal belongs at the fetch boundary, reader.cancel() at the consumption boundary, and cleanup code in transform flush/finally logic where state exists.
Field notes
TextDecoderwith{ stream: true }is mandatory for multi-byte characters split across chunks.- Browser support for stream constructors is good now, but Node/browser interop still trips teams; do not pass Node streams into browser piping APIs.
- A response body can be consumed once. Clone it with
response.clone()before two consumers race. - Streams compose beautifully with workers: transfer a
ReadableStreamor process chunks inside a worker rather than posting every chunk manually.
Was this lesson helpful?