Full answer
Streams let a program process data as it arrives instead of waiting for all of it. A ReadableStream is a source of chunks, a WritableStream is a destination, and a TransformStream is a pair that turns input chunks into output chunks. response.body from fetch is a ReadableStream of Uint8Array chunks, so text can start to be processed before the download ends. Large files, logs, and live feeds fit streaming well, and memory use depends on the chunk size, not on the total size.
stream.getReader() gives a reader whose read() returns { value, done }. pipeThrough(transform) and pipeTo(writable) connect streams and handle errors and closing. TextDecoderStream turns bytes into text, taking care of multi-byte characters split across chunks.
Backpressure is the flow-control rule. Each stream has a queue with a high water mark. When the queue is full, desiredSize drops to zero or below, and the producer should pause until the consumer reads. In pull-based sources, the pull() callback is only called when there is room, so a fast producer cannot flood a slow consumer. Piping applies this automatically.
The classic parsing pitfall is that a chunk is an arbitrary slice of bytes. A line, a JSON record, or even a character can be cut in the middle. A correct parser keeps a buffer: append the decoded chunk, split on the newline, emit all complete lines, and keep the last incomplete piece for the next chunk. After the stream ends, it must flush the remaining buffer.
Streams are single-consumer. Use tee() to create two branches, and cancel the reader when the consumer stops early so the producer can release resources.
const http = require('node:http');
const server = http.createServer((req, res) => {
const chunks = ['{"id":1}\n{"id"', ':2}\n{"i', 'd":3}\n{"id":4}'];
let index = 0;
const timer = setInterval(() => {
if (index < chunks.length) res.write(chunks[index++]);
else {
clearInterval(timer);
res.end(); // no trailing newline: the last record needs the flush step
}
}, 10);
});
function splitLines() {
let buffer = '';
return new TransformStream({
transform(text, controller) {
buffer += text;
const lines = buffer.split('\n');
buffer = lines.pop(); // keep the incomplete tail
for (const line of lines) if (line) controller.enqueue(line);
},
flush(controller) {
if (buffer) controller.enqueue(buffer);
},
});
}
server.listen(0, '127.0.0.1', async () => {
const response = await fetch(`http://127.0.0.1:${server.address().port}/`);
const rawChunks = [];
const records = response.body
.pipeThrough(new TransformStream({
transform(chunk, controller) {
rawChunks.push(chunk.length);
controller.enqueue(chunk);
},
}))
.pipeThrough(new TextDecoderStream())
.pipeThrough(splitLines());
const reader = records.getReader();
while (true) {
const { value, done } = await reader.read();
if (done) break;
console.log('record:', JSON.parse(value));
}
console.log('network chunks were received:', rawChunks.length > 0);
const log = [];
let produced = 0;
const source = new ReadableStream({
pull(controller) {
produced += 1;
log.push(`pull ${produced}`);
controller.enqueue(produced);
if (produced === 6) controller.close();
},
}, { highWaterMark: 2 });
const sourceReader = source.getReader();
await new Promise((resolve) => setTimeout(resolve, 20));
console.log('before any read, pulls already made:', log.length, '(highWaterMark is 2)');
const first = await sourceReader.read();
await new Promise((resolve) => setTimeout(resolve, 20));
console.log('after one read:', first.value, 'pulls so far:', log.length);
const encoded = new TextEncoder().encode('héllo');
const half = [encoded.slice(0, 2), encoded.slice(2)];
const naive = half.map((bytes) => new TextDecoder().decode(bytes)).join('');
const streaming = new TextDecoder();
const careful = streaming.decode(half[0], { stream: true }) + streaming.decode(half[1]);
console.log(JSON.stringify(naive), careful);
server.close();
server.closeAllConnections();
});Run with Node.js v24.22.1 as js-77.js; two runs gave identical output. Output: record: { id: 1 } record: { id: 2 } record: { id: 3 } record: { id: 4 } network chunks were received: true before any read, pulls already made: 2 (highWaterMark is 2) after one read: 1 pulls so far: 3 "h��llo" héllo
Key points
- Streams process data chunk by chunk, so memory does not grow with total size.
- response.body is a ReadableStream of bytes; pipeThrough and pipeTo connect stages.
- Backpressure: a full queue pauses the producer until the consumer reads.
- Chunks do not align with records; buffer the incomplete tail and flush at the end.
- Use TextDecoderStream for correct multi-byte decoding and cancel early to release resources.
Common mistakes
- Assuming each chunk contains complete lines or records.
- Forgetting to flush the leftover buffer when the stream ends.
- Decoding bytes with a fresh TextDecoder for each chunk, which breaks multi-byte characters.
- Reading the whole body into memory with response.text() when the data is large.
Follow-ups
- How does tee() affect memory when one branch reads more slowly than the other?
- How would you cancel a download when the consumer no longer needs the data?
- How do Node.js streams differ from web streams?
Tips
- Describe backpressure as "a full queue tells the producer to wait"; then name highWaterMark.
- Show the tail buffer for line parsing; it is the standard real-world bug.
- Mention TextDecoderStream for multi-byte safety.