Skip to main content

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.stdout in some contexts
  • crypto.createCipher() / createDecipher() (encryption/decryption)

The relationship between stream types

Stream typeCan read?Can write?
ReadableYesNo
WritableNoYes
DuplexYesYes
TransformYesYes (but changes the data as it passes through)

A Duplex Stream example

Node.js provides a base class, stream.Duplex, that can be extended:

javascript
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:

javascript
Read: Hello Read: from Read: Duplex! Written: Hello Written: World

How 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:

CriterionDuplexTransform
The link between input and outputIndependentThe input becomes the output
ExampleA TCP socketgzip compression, JSON parsing
Methods_read() + _write()_transform()

Examples of built-in Duplex streams

ModuleExample
netnet.Socket (two-way data transfer)
tlstls.TLSSocket
cryptocrypto.Cipher, crypto.Decipher
zlibzlib.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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.