Sobes.tech
Middle+

What is the purpose of a Duplex stream?

sobes.tech AI

Answer from AI

A Duplex stream is a data stream that supports bidirectional data transfer: you can read and write data simultaneously.

In frontend development, this is useful, for example, when working with WebSocket or network connections, where the client and server exchange messages in real time.

An example of using Duplex stream in Node.js:

const { Duplex } = require('stream');

class EchoStream extends Duplex {
  _write(chunk, encoding, callback) {
    this.push(chunk); // send back what was received
    callback();
  }

  _read(size) {}
}

const echo = new EchoStream();
echo.on('data', (chunk) => {
  console.log('Received:', chunk.toString());
});
echo.write('Hello');

Thus, Duplex stream allows organizing interactive data exchange within a single object.

What is the purpose of a Duplex stream? — Frontend - sobes.tech