Categories
JavaScript Answers

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

Spread the love

Sometimes, we want to pipe the same readable stream into multiple writable targets with Node.js and JavaScript.

In this article, we’ll look at how to pipe the same readable stream into multiple writable targets with Node.js and JavaScript.

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

To pipe the same readable stream into multiple writable targets with Node.js and JavaScript, we can use the PassThrough object.

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 PassThrough objects b and c.

Then we call a.stdout.pipe with them to pipe them to b and c.

Next we listen for data events on b to get the chunks.

And then when the end event is triggered on b, we call c.pipe with process.stdout to pipe process.stdout to c.

Conclusion

To pipe the same readable stream into multiple writable targets with Node.js and JavaScript, we can use the PassThrough object.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.