A Node.js stream lets your code read or write data piece by piece as chunks arrive instead of loading an entire gigabyte file into memory at once. Streams power fs.createReadStream(), HTTP request/response bodies, and zlib compression pipelines.
pipeline()Node.js organizes streams into four interfaces depending on data direction:
fs.createReadStream(), http.IncomingMessage).fs.createWriteStream(), http.ServerResponse).zlib.createGzip(), crypto ciphers).Always connect streams with pipeline() from node:stream/promises instead of .pipe(). pipeline() automatically handles backpressure (pausing fast readers when disk writes lag) and cleans up all stream handles if any step errors.
import { createReadStream, createWriteStream } from 'node:fs';
import { createGzip } from 'node:zlib';
import { pipeline } from 'node:stream/promises';
async function compressLogFile(inputPath, outputPath) {
await pipeline(
createReadStream(inputPath),
createGzip(),
createWriteStream(outputPath)
);
console.log('Compression complete:', outputPath);
}
for await...ofReadable streams implement JavaScript's async iterator protocol, letting you process chunks cleanly with for await (const chunk of readable) without wrestling with 'data' and 'end' event listeners.
.pipe() without error handlers on every stream: If the source file fails mid-stream, .pipe() does not destroy downstream streams or propagate errors, leaking file descriptors. Always use pipeline().writable.write(chunk) === false buffers gigabytes in RAM; await 'drain' or use pipeline().Readable.from() for quick in-memory streams: Readable.from(['line1 ', 'line2 ']) turns any array or async generator directly into a stream.By default, fs.createReadStream() reads 64 KB chunks (highWaterMark: 64 * 1024), keeping RAM usage flat even on a 10 GB file.
Backpressure is the signal from a slow writable destination (like disk or network) telling a fast readable source to pause reading until the write buffer drains.
ReadableStream?Yes. Readable.toWeb() and Readable.fromWeb() bridge Node streams with fetch() Web Streams cleanly.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.