Composing duplex streams

A duplex stream is a stream with a readable and writable interface. We can take a readable stream and a writeable stream and join them as a duplex stream using the duplexify module.

Let's create a folder called composing-duplex-streams, initialize it as a package, install from2, to2, and duplexify, and create an an index.js file:

$ mkdir composing-duplex-streams 
$ cd composing-duplex-streams
$ npm init -y
$ npm install --save from2 to2 duplexify
$ touch index.js

Then in our index.js file we'll write:

const from = require('from2') 
const to = require('to2')
const duplexify = require('duplexify')

const rs = from(() => {
rs.push(Buffer.from('Hello, World!'))
rs.push(null)
})

const ws = to((data, enc, cb) => {
console.log(`Data written: ${data.toString()}`)
cb()
})

const stream = duplexify(ws, rs)

stream.pipe(stream)

We're using the same readable and writable streams from the main recipe (rs and ws); however, we create the stream assignment by passing ws and rs to duplexify. Now instead of piping rs to ws, we can pipe stream to itself.

This can be a very useful API pattern when we want to return or export two streams that are interrelated in some way.