Node.js Streams: Processing Large Data Without Running Out of Memory

Process gigabytes with megabytes of memory

Reading a 5 GB file with fs.readFile will crash your process. Streams process data piece by piece, keeping memory flat no matter how large the input.

The Four Stream Types

  • Readable — a source: file read, HTTP request, database cursor
  • Writable — a destination: file write, HTTP response
  • Duplex — both: TCP socket
  • Transform — modifies data passing through: compression, parsing

Always Use pipeline

import { pipeline } from 'node:stream/promises';
import { createReadStream, createWriteStream } from 'node:fs';
import { createGzip } from 'node:zlib';

await pipeline(
  createReadStream('logs.txt'),
  createGzip(),
  createWriteStream('logs.txt.gz')
);

pipeline handles errors and cleanup for every stream. Avoid chaining .pipe() without error handling.

Backpressure

If a writer is slower than the reader, data piles up in memory. Streams handle this automatically through backpressure — the reader pauses until the writer catches up. Using pipeline gives you this for free.

Custom Transform

import { Transform } from 'node:stream';

const upperCase = new Transform({
  transform(chunk, encoding, callback) {
    callback(null, chunk.toString().toUpperCase());
  },
});

Async Iteration

Readable streams are async iterables — very readable code:

import { createReadStream } from 'node:fs';
import { createInterface } from 'node:readline';

const rl = createInterface({ input: createReadStream('big.csv') });
let count = 0;
for await (const line of rl) {
  if (line.includes('ERROR')) count++;
}
console.log(`Errors: ${count}`);

Real-World Uses

  • Uploading and downloading large files to S3
  • Exporting millions of database rows to CSV
  • Streaming HTTP responses (including AI token streams)
  • Log processing and ETL pipelines

Web Streams

Node.js also supports the Web Streams API (ReadableStream), used by fetch. Convert with Readable.fromWeb() and Readable.toWeb() when mixing APIs.

If data might be large, stream it. It's the difference between a service that scales and one that crashes at the worst moment.

Arivanandhan Chitheshwaran