Intermediate Node.js Interview QuestionsIntermediateConcept
Node.js · Question 50
What are the types of streams in Node.js?
Direct answer
Node has four stream types — Readable (source), Writable (destination), Duplex (both, e.g. TCP socket), and Transform (Duplex that modifies data, e.g. gzip); all extend EventEmitter and implement the stream API.
Classifying streams by data direction helps pick the right API and debug flow — interviewers often ask which type fits a file read vs HTTP proxy vs encryption.
| Type | Direction | Examples |
|---|---|---|
| Readable | Read only | fs.createReadStream, http.IncomingMessage |
| Writable | Write only | fs.createWriteStream, http.ServerResponse |
| Duplex | Read + write independent | net.Socket, TLS socket |
| Transform | Read → transform → write | zlib.createGzip, crypto.createCipheriv |
- Object mode — streams push JS objects instead of Buffers/strings when objectMode: true.
- Legacy vs web — Node stream API; also stream/web ReadableStream in fetch.
- HighWaterMark — internal buffer threshold before backpressure kicks in (Q53).
stream-types.mjs
import { Readable, Writable, Transform } from "node:stream";
const source = Readable.from(["line1\n", "line2\n"]);
const upper = new Transform({
transform(chunk, enc, cb) {
cb(null, chunk.toString().toUpperCase());
},
});
const sink = new Writable({
write(chunk, enc, cb) {
process.stdout.write(chunk);
cb();
},
});
source.pipe(upper).pipe(sink);