Full answer
The four stream classes form a family:
- Readable: you produce data (_read, push).
- Writable: you consume data (_write, _final).
- Duplex: both, with no relationship between the two sides. A TCP socket is the standard example. Writes go to the peer, and reads come from the peer.
- Transform: a Duplex whose readable side is the result of the writable side (_transform, _flush).
- PassThrough: a Transform that does nothing. It is useful as a tap, a placeholder, or a way to connect code that wants a stream to code that produces one later.
Building a Duplex:
- Implement _read(size) and call push(data) or push(null) at the end of the readable side.
- Implement _write(chunk, encoding, callback) for the writable side.
- Optionally implement _final(callback) to run when the writer calls end(), and _destroy for cleanup.
- Each side has its own buffer, its own highWaterMark and its own backpressure. allowHalfOpen (default true) means one side can end while the other continues.
Helpers:
- Duplex.from(asyncGeneratorFunction) makes a Duplex that reads from the writable side and yields to the readable side.
- stream.compose(a, b, c) joins streams into a single Duplex. Writing goes to the first stage and reading comes from the last. It is useful for reusable pipelines that you can pass around.
- Duplex.toWeb and Duplex.fromWeb convert to and from Web Streams.
Design tip: if the output depends on the input, use Transform. If two independent flows share one object, such as a protocol connection or a fake device in a test, use Duplex.
javascript
const { Duplex, Transform, PassThrough, Readable, compose } = require('node:stream');
const { pipeline } = require('node:stream/promises');
// A fake device: commands written to it are stored, and it separately "reports" three readings.
class FakeDevice extends Duplex {
constructor() {
super({ encoding: 'utf8' });
this.commands = [];
this.count = 0;
}
_read() {
this.count < 3 ? this.push(`reading-${++this.count}\n`) : this.push(null);
}
_write(chunk, encoding, callback) {
this.commands.push(chunk.toString());
callback();
}
_final(callback) {
this.commands.push('(writer ended)');
callback();
}
}
async function main() {
const device = new FakeDevice();
device.write('start');
device.end('stop');
let output = '';
for await (const piece of device) output += piece;
console.log('written to device :', JSON.stringify(device.commands));
console.log('read from device :', JSON.stringify(output));
// PassThrough copies; Transform changes.
const tap = new PassThrough();
const seen = [];
tap.on('data', (c) => seen.push(c.toString()));
tap.end('same text');
await new Promise((resolve) => tap.on('end', resolve));
console.log('PassThrough output:', seen.join(''));
// compose joins two stages into one Duplex that can be reused.
const upper = new Transform({ transform(c, e, cb) { cb(null, c.toString().toUpperCase()); } });
const exclaim = new Transform({ transform(c, e, cb) { cb(null, c.toString() + '!'); } });
const shout = compose(upper, exclaim);
console.log('compose is a Duplex:', shout instanceof Duplex);
shout.end('hello');
let shouted = '';
for await (const piece of shout) shouted += piece;
console.log('composed result:', shouted);
// Duplex.from with an async generator.
const numbered = Duplex.from(async function* (source) {
let n = 0;
for await (const chunk of source) yield `${++n}:${chunk}`;
});
const parts = [];
await pipeline(Readable.from(['a', 'b']), numbered, async (source) => { for await (const p of source) parts.push(p); });
console.log('Duplex.from result:', parts.join(' '));
}
main();The device receives commands and produces readings on separate sides. compose and Duplex.from build reusable stages. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): written to device : ["start","stop","(writer ended)"] read from device : "reading-1\nreading-2\nreading-3\n" PassThrough output: same text compose is a Duplex: true composed result: HELLO! Duplex.from result: 1:a 2:b
Key points
- Duplex has two independent sides; Transform ties output to input.
- PassThrough copies input to output unchanged.
- A Duplex needs _read and _write, and often _final.
- Duplex.from and compose create reusable stream units.
- Each side has its own buffer and backpressure.
Common mistakes
- Using Duplex when a Transform was meant, and reading data that was never produced.
- Forgetting _final, so the writer's end() has no effect on the device.
- Ending the readable side with push(null) and expecting the writable side to close.
- Not realising that each side has its own highWaterMark.
- Calling push() after push(null).
Follow-ups
- What does allowHalfOpen change for a socket?
- How do you convert a Node stream to a Web Stream?
- When would you use PassThrough in real code?
Tips
- Use the socket as the example for Duplex.
- Say 'two independent sides' clearly.
- Mention compose and Duplex.from as modern tools.