What are the four types of streams in Node.js?
Readable (data source, like a file read), Writable (destination, like a file write or HTTP response), Duplex (both, like a TCP socket), and Transform (a duplex that changes data as it passes, like gzip).
Explain it simply
Think of water pipes. A tap is a Readable: water comes out. A bucket is a Writable: water goes in. A Duplex is a two-way pipe, like a phone line where both people talk. A Transform is a filter in the middle that changes the water as it passes through, for example a RO purifier.
| Type | Direction | Examples |
|---|---|---|
| Readable | out | fs.createReadStream, incoming HTTP request on the server |
| Writable | in | fs.createWriteStream, HTTP response, process.stdout |
| Duplex | both, independent | TCP socket (net.Socket) |
| Transform | both, output derived from input | zlib.createGzip(), crypto.createCipheriv() |
Example
const fs = require("fs");
const zlib = require("zlib");
const { pipeline } = require("stream");
pipeline(
fs.createReadStream("marks.csv"), // Readable
zlib.createGzip(), // Transform
fs.createWriteStream("marks.csv.gz"), // Writable
(err) => {
if (err) console.error("failed", err);
else console.log("compressed");
}
);All streams are event emitters. Readable streams emit data and end; writable streams have write(), end(), and emit finish.
What to say in the interview
"Readable produces data, Writable consumes it, Duplex does both independently, and Transform is a duplex whose output depends on its input. I chain them with pipeline so errors are handled and resources cleaned up."
Common mistakes
- Calling a Transform just a Duplex without saying output is computed from input.
- Chaining with plain
.pipe()and missing errors.