Creating a Basic Duplex Stream
You'll learn how to build your own duplex stream by implementing both _read and _write methods to handle bidirectional data flow.
The Core Idea
A duplex stream is like a two-way radio: you can both speak and listen at the same time. To create a custom duplex stream in Node.js, you extend the Duplex class and implement two methods:
_read(size)— defines how your stream produces data when someone reads from it_write(chunk, encoding, callback)— defines how your stream handles incoming data when someone writes to it
These methods work independently, meaning data flowing in doesn't have to affect data flowing out.
Basic Implementation Pattern
const { Duplex } = require('stream');
class BasicDuplex extends Duplex {
_read(size) {
// Push data to the readable side
// Called when someone wants to read from this stream
this.push('some data');
this.push(null); // Signal end of data
}
_write(chunk, encoding, callback) {
// Handle incoming data on the writable side
// Called when someone writes to this stream
console.log('Received:', chunk.toString());
callback(); // Signal write is complete
}
}
const myDuplex = new BasicDuplex();
// Use it as writable
myDuplex.write('Hello!');
// Use it as readable
myDuplex.on('data', chunk => {
console.log('Read:', chunk.toString());
});
Notice how _read and _write operate independently—they're two separate channels in one stream object.
Key Takeaway: To create a duplex stream, extend the Duplex class and implement both _read() to supply data and _write() to consume data, enabling bidirectional communication through a single stream instance.