Categories
JavaScript Answers

How to pipe the same readable stream into multiple (writable) targets with Node.js?

Spread the love

To pipe the same readable stream into multiple (writable) targets with Node.js, we call the pipe method on each stream.

For instance, we write

const spawn = require("child_process").spawn;
const PassThrough = require("stream").PassThrough;

const a = spawn("echo", ["hi user"]);
const b = new PassThrough();
const c = new PassThrough();

a.stdout.pipe(b);
a.stdout.pipe(c);

let count = 0;
b.on("data", (chunk) => {
  count += chunk.length;
});
b.on("end", () => {
  console.log(count);
  c.pipe(process.stdout);
});

to create 2 PassThrough objects.

Then we call pipe to pipe our input from a to to the PassThrough objects with pipe to write to them.

We get the data written from the 'data' event handler’s chunk parameter.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *