Duplex Stream in Node.js: What It Is and How It Works
duplex stream in Node.js is a type of stream that can both read and write data. It acts like a two-way pipe, allowing data to flow in and out independently, making it useful for scenarios like network sockets or file operations where you need simultaneous input and output.How It Works
Think of a duplex stream as a two-way street for data. It can send data out (write) and receive data in (read) at the same time, independently. This is different from a simple readable stream (which only outputs data) or a writable stream (which only accepts data).
Imagine a telephone call: you can talk and listen simultaneously. A duplex stream works the same way in Node.js, allowing your program to handle incoming and outgoing data streams without waiting for one to finish before starting the other.
Under the hood, a duplex stream inherits from both readable and writable streams, combining their abilities. This makes it perfect for things like network connections, where data flows both ways continuously.
Example
This example shows a simple duplex stream that echoes back any data it receives, demonstrating both reading and writing.
import { Duplex } from 'stream'; class EchoDuplex extends Duplex { _read(size) { // No need to implement reading logic here for this example } _write(chunk, encoding, callback) { // Write back the received chunk this.push(chunk); callback(); } _final(callback) { this.push(null); // Signal end of readable stream callback(); } } const echo = new EchoDuplex(); echo.on('data', (chunk) => { console.log('Received:', chunk.toString()); }); echo.write('Hello, duplex stream!'); echo.end();
When to Use
Use duplex streams when you need to handle data flowing in both directions at the same time. Common real-world uses include:
- Network sockets where your app sends and receives messages simultaneously.
- Protocols like HTTP/2 or WebSockets that require two-way communication.
- Custom streams that transform data while reading and writing.
They help keep your code efficient and clean by managing input and output in one place without blocking either side.
Key Points
- A duplex stream can read and write data independently at the same time.
- It combines readable and writable stream features in one object.
- Ideal for two-way communication like network connections.
- Implement
_readand_writemethods to customize behavior.