Streams process data in chunks instead of loading entire files into memory—essential for large uploads, logs, and proxying HTTP responses.
Stream types
- Readable — source (file read, HTTP response body)
- Writable — sink (file write, HTTP response)
- Transform — modify data in flight (gzip, CSV parser)
- Duplex — both directions (TCP socket)
Pipeline
import { pipeline } from 'node:stream/promises';
import { createReadStream, createWriteStream } from 'node:fs';
await pipeline(
createReadStream('big.log'),
createWriteStream('copy.log')
);
Important interview questions and answers
- Q: Why streams for large files?
A: Constant memory usage—process chunk by chunk instead of buffering gigabytes in RAM. - Q: backpressure?
A: When writable cannot keep up, readable pauses—streams coordinate flow automatically when piped correctly.
Self-check
- Name two stream types.
- When prefer pipeline over readFile?