Understanding streams

Topic 1 of 3 in Streams7 min readIntermediateFree course

Overview

Imagine your API needs to export a 3 GB CSV file. With readFile, Node loads all 3 GB into memory before it can send a byte — your server runs out of memory, and the user waits for ages before the download starts.

Streams solve this. Instead of handling data all at once, a stream handles it in small chunks (64 KB by default for files). Each chunk is processed and passed on, then discarded. Memory stays small and flat, and processing starts immediately.

Streams are everywhere in Node: an HTTP request body is a stream, so is the response, so are files, network sockets, process.stdin and process.stdout, compression and encryption.

Four kinds of stream

Readable streams produce data, for example fs.createReadStream, an HTTP request or process.stdin. Writable streams consume data, for example fs.createWriteStream, an HTTP response or process.stdout. Duplex streams do both independently, like a network socket. Transform streams change data as it passes through, like gzip compression or a CSV parser.

Type Data… Examples
Readable comes out of it fs.createReadStream, HTTP req, process.stdin
Writable goes into it fs.createWriteStream, HTTP res, process.stdout
Duplex goes both ways, independently TCP sockets
Transform goes in, gets changed, comes out zlib.createGzip(), encryption, parsers

Every stream is an EventEmitter, so it emits events such as 'data', 'end', 'error' and 'finish'.

Reading a stream

The easiest way is for await…of — a readable stream is an async iterable of chunks:

JavaScript
import { createReadStream } from 'node:fs';

let bytes = 0;
for await (const chunk of createReadStream('video.mp4')) {
  bytes += chunk.length; // chunk is a Buffer, about 64 KB
}
console.log(`${bytes} bytes`);

Pass an encoding to receive strings instead of Buffers: createReadStream('notes.txt', { encoding: 'utf8' }).

The event style

You’ll see the older event-based style in many codebases:

JavaScript
const stream = createReadStream('video.mp4');
stream.on('data', (chunk) => { bytes += chunk.length; });
stream.on('end', () => console.log('done'));
stream.on('error', (err) => console.error(err));

Both work. for await is shorter, handles errors with ordinary try…catch, and naturally waits when your processing is slow.

Reading line by line

readline turns a stream of chunks into a stream of lines — perfect for logs and CSV files:

JavaScript
import { createInterface } from 'node:readline';

const rl = createInterface({ input: createReadStream('access.log'), crlfDelay: Infinity });
for await (const line of rl) {
  if (line.includes(' 500 ')) console.log(line);
}

Writing a stream

JavaScript
import { createWriteStream } from 'node:fs';

const out = createWriteStream('report.csv');
out.write('id,name\n');
for (const user of users) {
  out.write(`${user.id},${user.name}\n`);
}
out.end(); // no more data; flush and close
out.on('finish', () => console.log('saved'));

end() says “that’s everything”. The 'finish' event fires once all data has been written.

Backpressure

What happens when the readable side is faster than the writable side — say, reading from a fast SSD and sending over a slow mobile connection? Without care, data piles up in memory waiting to be written, and the whole point of streaming is lost.

A readable stream reading from disk at 500 MB/s feeds an internal buffer before a writable stream sending over the network at 5 MB/s. When the buffer reaches its highWaterMark, write() returns false and the reader pauses until the writer drains. pipe() and pipeline() do this automatically.

Every writable stream has a buffer limit called the highWaterMark. When it’s full, write() returns false — a signal to stop and wait for the 'drain' event before writing more. This is backpressure:

JavaScript
import { once } from 'node:events';

for (const row of hugeListOfRows) {
  if (!out.write(row)) {
    await once(out, 'drain'); // wait until the writer has caught up
  }
}
out.end();

The good news: you rarely write this by hand. pipe() and pipeline() (next topic) handle backpressure automatically.

Streams in HTTP

An Express or http response (res) is a writable stream, so you can stream a file straight to the browser:

JavaScript
import { createReadStream } from 'node:fs';
import { pipeline } from 'node:stream/promises';

app.get('/download', async (req, res) => {
  res.setHeader('Content-Type', 'text/csv');
  res.setHeader('Content-Disposition', 'attachment; filename="export.csv"');
  await pipeline(createReadStream('exports/big.csv'), res);
});

The download starts instantly and the server’s memory use stays the same whether the file is 1 MB or 10 GB.

The incoming request (req) is a readable stream too — that’s how upload handling and body parsers work under the hood.

Creating readable streams from data

Readable.from turns any iterable or async iterable into a stream — handy for streaming data you generate:

JavaScript
import { Readable } from 'node:stream';

async function* rows() {
  yield 'id,name\n';
  for await (const user of db.streamUsers()) {
    yield `${user.id},${user.name}\n`;
  }
}

await pipeline(Readable.from(rows()), res);

Readable helpers

Readable streams also have array-like helper methods that work chunk by chunk:

JavaScript
const big = createReadStream('data.ndjson', { encoding: 'utf8' })
  .filter((chunk) => chunk.includes('"status":"failed"'))
  .map((chunk) => chunk.toUpperCase());

And node:stream/consumers collects a whole stream when you know it’s small:

JavaScript
import { json, text } from 'node:stream/consumers';
const body = await json(req); // parse a small JSON request body

When to stream: whenever data might be large, or arrives over time. Files bigger than a few megabytes, exports, uploads, proxying responses, and logs are all natural fits.

Exercise

Count lines in a huge file

Write countLines(file) that counts the newline characters in a file using a read stream, so it works for files far larger than your memory. Compare memory use with a readFile version on a large file.

JavaScript
import { createReadStream } from 'node:fs';

export async function countLines(file) {
  // your code here
}

Summary

  • Streams move data in small chunks, so memory use stays flat however large the data is.
  • There are four kinds: Readable, Writable, Duplex and Transform.
  • Read a stream with for await…of, or with 'data'/'end' events.
  • write() returning false means slow down; wait for 'drain' — this is backpressure.
  • HTTP requests and responses, files, sockets and stdin/stdout are all streams.