What are streams in Node, and what are the four types?
3 minintermediatenodejsstreamsreadablewritabletransform
Quick Answer
Streams process data in chunks over time instead of loading it all into memory. The four types are Readable (source, e.g. fs.createReadStream), Writable (sink, e.g. HTTP response), Duplex (both, e.g. a TCP socket), and Transform (a Duplex that modifies data, e.g. zlib gzip).
Detailed Answer
Answer:
A stream is an abstraction for reading or writing data incrementally — piece by piece — rather than holding the whole payload in memory. Streams are EventEmitters.
The four types:
| Type | Direction | Examples |
|---|---|---|
| Readable | source you read from | fs.createReadStream, HTTP request, process.stdin |
| Writable | sink you write to | fs.createWriteStream, HTTP response, process.stdout |
| Duplex | both, independent | TCP socket (net.Socket) |
| Transform | Duplex that transforms input→output | zlib.createGzip, crypto cipher streams |
Reading and writing:
const fs = require('fs');
const rs = fs.createReadStream('input.txt');
const ws = fs.createWriteStream('output.txt');
rs.on('data', chunk => ws.write(chunk));
rs.on('end', () => ws.end());
rs.on('error', err => console.error(err));
The idiomatic version — pipe:
fs.createReadStream('input.txt')
.pipe(zlib.createGzip()) // Transform
.pipe(fs.createWriteStream('input.txt.gz'));
Why streams matter: they keep memory usage constant and low regardless of file/response size and start producing output before all input has arrived (lower latency). They're everywhere in Node — HTTP bodies, file I/O, compression, crypto.