Stream (Node.js)

A stream in Node.js processes data piece by piece instead of loading it all into memory at once. Readable, Writable, Duplex, and Transform streams let you handle large files and network data efficiently.

Node.js

Streams handle data that arrives or departs over time, in chunks. Rather than reading a 2 GB file fully into memory, a readable stream emits manageable chunks, keeping memory use low and letting processing start before all data has arrived. This makes streams essential for large files, uploads, and network I/O.

There are four types: Readable (sources you read from, like a file read stream or HTTP request), Writable (destinations you write to, like a file or HTTP response), Duplex (both), and Transform (a duplex that modifies data passing through, like gzip). They are EventEmitters, emitting 'data', 'end', and 'error'.

The .pipe() method (or the modern pipeline() helper) connects a readable to a writable and handles backpressure — pausing the source when the destination is slow — automatically. Piping a read stream to a write stream is the idiomatic way to copy or transform large data with minimal memory.

Syntax

readable.pipe(writable);

Examples

JavaScript

const fs = require("fs");

// copy a large file chunk-by-chunk, low memory
fs.createReadStream("big.log")
  .pipe(fs.createWriteStream("copy.log"))
  .on("finish", () => console.log("done"));

Learn it in a lesson

See also

Back to the Dictionary