What is a Duplex stream?
A Duplex Stream is a Node.js stream that is both Readable and Writable at once, meaning it can both read and write data.
If Readable is a data source and Writable is a destination,
Duplex combines both roles, source and destination, in one object.
A real-life example
You can picture a Duplex Stream as a two-way pipe: something gets written in one end, and read out the other.
This is how, for example, these work:
- a TCP socket (
net.Socket) - a WebSocket connection
process.stdin+process.stdoutin some contextscrypto.createCipher()/createDecipher()(encryption/decryption)
The relationship between stream types
| Stream type | Can read? | Can write? |
|---|---|---|
| Readable | Yes | No |
| Writable | No | Yes |
| Duplex | Yes | Yes |
| Transform | Yes | Yes (but changes the data as it passes through) |
A Duplex Stream example
Node.js provides a base class, stream.Duplex, that can be extended:
const { Duplex } = require('stream');
class MyDuplex extends Duplex {
constructor(options) {
super(options);
this.data = ['Hello', 'from', 'Duplex!'];
}
// Implement reading
_read() {
if (this.data.length === 0) {
this.push(null); // signal the end
} else {
const chunk = this.data.shift();
this.push(chunk);
}
}
// Implement writing
_write(chunk, encoding, callback) {
console.log('Written:', chunk.toString());
callback(); // the callback must be called!
}
}
const duplex = new MyDuplex();
duplex.on('data', (chunk) => {
console.log('Read:', chunk.toString());
});
duplex.write('Hello');
duplex.write('World');
duplex.end();Result:
Read: Hello
Read: from
Read: Duplex!
Written: Hello
Written: WorldHow a Duplex Stream works
A Duplex stream has two independent buffers:
- one for reading (
readableBuffer), - another for writing (
writableBuffer).
That means reading and writing can happen asynchronously and independently: data can be written to the stream without waiting for it to read anything, and vice versa.
Duplex vs Transform
Both can read and write, but the difference is:
| Criterion | Duplex | Transform |
|---|---|---|
| The link between input and output | Independent | The input becomes the output |
| Example | A TCP socket | gzip compression, JSON parsing |
| Methods | _read() + _write() | _transform() |
Examples of built-in Duplex streams
| Module | Example |
|---|---|
net | net.Socket (two-way data transfer) |
tls | tls.TLSSocket |
crypto | crypto.Cipher, crypto.Decipher |
zlib | zlib.Deflate, zlib.Inflate |
Advantages of Duplex Streams
- Two-way communication (reading and writing at once)
- Used for network and encryption operations
- Efficiently handles large volumes of data
- Can be combined with other streams via
.pipe()
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.