TExcelTAD
Home › Node.js › Node.js Streams

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:

node · try it yourself
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:

node · try it yourself
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:

node
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 older a.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:

node · try it yourself
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:

node · try it yourself
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()?

  1. Readable
  2. Writable
  3. Transform
  4. It is not a stream

What does it mean when writable.write(chunk) returns false?

  1. The write failed
  2. The stream is closed
  3. The internal buffer is full; wait for 'drain'
  4. The chunk was empty

Why prefer pipeline() over .pipe()?

  1. It is synchronous
  2. It forwards errors and cleans up every stream
  3. It only works with files
  4. It buffers the whole input first