Chuck's Academy

Streaming and Buffering in Node

Duplex Streams in Node.js

What is a Duplex Stream?

A duplex stream is a stream that is both readable and writable. This means you can read and write data in the same stream. Duplex streams are useful for scenarios where you want to combine reading and writing functionality, such as bidirectional communication in networks (sockets) and real-time file and data stream manipulation.

Creating a Duplex Stream

To create a duplex stream, you can extend the Duplex class from the stream module and override the _read and _write methods.

Basic Example

javascript

In this example, MyDuplexStream stores the written data in an array and emits it when read.

Using Duplex Streams

Below is how to use MyDuplexStream to write and then read data.

javascript

Practical Example: Sockets

A common application for duplex streams is bidirectional communication in networks. Here is a simple example using network sockets.

javascript

In this example, the server creates a duplex stream for each socket connection, allowing data to be read and written in both directions.

Benefits of Using Duplex Streams

  • Versatility: Enables data input and output in a single stream.
  • Convenience: Simplifies the logic for applications that require both reading and writing data.
  • Efficiency: Ideal for network and real-time applications.

Summary

Duplex streams are a powerful tool in Node.js for handling bidirectional data flows. Whether for networks, file manipulation, or real-time processing, their ability to read and write data in the same stream simplifies and optimizes the development of complex applications.

Diagram of Duplex StreamsDiagram of Duplex Streams


Ask me anything