Node.js Streams
fs.readFile() loads a whole file into memory before you can touch a single byte. That's fine for a config file, but not for a 4 GB log, a video upload, or an HTTP response you want to start sending immediately. Streams process data piece by piece — in chunks — so memory use stays small and work starts right away.
Streams are everywhere in Node.js: req and res in an HTTP server, process.stdin and process.stdout, file reads and writes, compression in zlib, and hashing in crypto.
The four kinds of streams
| Type | Direction | Examples |
|---|---|---|
| Readable | you read data from it | fs.createReadStream(), req in a server, process.stdin |
| Writable | you write data to it | fs.createWriteStream(), res in a server, process.stdout |
| Duplex | both, independently | TCP sockets |
| Transform | duplex where output is computed from input | zlib.createGzip(), crypto.createHash() |
All streams are EventEmitters. They live in node:stream; the promise-based helpers are in node:stream/promises.
Reading a stream with for await
The modern way to consume a readable stream is an async iterator. The example first writes a small file, then reads it back in tiny chunks (highWaterMark sets the chunk size, normally 64 KiB) to make the chunking visible:
import { writeFile, rm } from 'node:fs/promises';
import { createReadStream } from 'node:fs';
await writeFile('poem.txt', 'Streams flow\nchunk by chunk\n');
const stream = createReadStream('poem.txt', { encoding: 'utf8', highWaterMark: 10 });
let count = 0;
for await (const chunk of stream) {
count++;
console.log(count, JSON.stringify(chunk));
}
console.log('done after', count, 'chunks');
await rm('poem.txt');1 "Streams fl"
2 "ow\nchunk b"
3 "y chunk\n"
done after 3 chunks
Older code uses events instead: stream.on('data', chunk => …), stream.on('end', …) and stream.on('error', …). Both styles work; for await is shorter and propagates errors with normal try…catch.
Writing to a stream
A writable stream has write(chunk) and end([chunk]). Wait for the 'finish' event (or use finished() from node:stream/promises) before you rely on the data being written:
import { createWriteStream } from 'node:fs';
import { readFile, rm } from 'node:fs/promises';
import { finished } from 'node:stream/promises';
const out = createWriteStream('log.txt');
for (let i = 1; i <= 3; i++) {
out.write(`line ${i}\n`);
}
out.end('the end\n');
await finished(out);
console.log(await readFile('log.txt', 'utf8'));
await rm('log.txt');line 1
line 2
line 3
the end
Backpressure and pipeline()
What if the reader is faster than the writer — say, reading from a fast disk and uploading over a slow network? write() returns false when the writable's internal buffer is full, and you should pause until it emits 'drain'. This flow control is called backpressure.
You rarely implement it yourself. pipeline() connects streams, handles backpressure, forwards errors and cleans up all streams when one fails:
import { pipeline } from 'node:stream/promises';
import { createReadStream, createWriteStream } from 'node:fs';
import { createGzip } from 'node:zlib';
await pipeline(
createReadStream('access.log'),
createGzip(),
createWriteStream('access.log.gz'),
);
console.log('compressed');Tip: Prefer
pipeline()over the oldera.pipe(b).pipe(c). With.pipe(), an error in one stream does not close the others, which can leak file handles.
Your own Transform stream
A transform receives chunks, changes them and pushes the result. This one upper-cases text. Readable.from() turns any array or iterable into a readable stream, which is handy for examples and tests:
import { Readable, Transform, Writable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
const upper = new Transform({
transform(chunk, encoding, callback) {
callback(null, chunk.toString().toUpperCase());
},
});
const collected = [];
const sink = new Writable({
write(chunk, encoding, callback) {
collected.push(chunk.toString());
callback();
},
});
await pipeline(Readable.from(['hello ', 'streaming ', 'world']), upper, sink);
console.log(collected);
console.log(collected.join(''));[ 'HELLO ', 'STREAMING ', 'WORLD' ]
HELLO STREAMING WORLD
pipeline() also accepts async generator functions as transform steps, which is often even simpler:
import { Readable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
const lines = ['apple,3', 'pear,0', 'kiwi,12'];
await pipeline(
Readable.from(lines),
async function* (source) {
for await (const line of source) {
const [fruit, qty] = line.split(',');
if (Number(qty) > 0) yield `${fruit.padEnd(6)}${qty.padStart(3)}\n`;
}
},
process.stdout,
);apple 3
kiwi 12
Stream events and methods
| Readable | Writable |
|---|---|
'data', 'end', 'error', 'close' events |
'drain', 'finish', 'error', 'close' events |
for await (const chunk of r) |
w.write(chunk) → false means "slow down" |
r.setEncoding('utf8') |
w.end(lastChunk) |
r.pause() / r.resume() |
w.destroy(err) |
Test yourself
Which stream type is zlib.createGzip()?
- Readable
- Writable
- Transform
- It is not a stream
What does it mean when writable.write(chunk) returns false?
- The write failed
- The stream is closed
- The internal buffer is full; wait for
'drain' - The chunk was empty
Why prefer pipeline() over .pipe()?
- It is synchronous
- It forwards errors and cleans up every stream
- It only works with files
- It buffers the whole input first