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 chunk
s.
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.