Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clone a NodeJS stream?

I need to somehow clone a readstream in nodeJS. That is if I have a readStream I need two copies of it stream1, stream2. Where I can read both the streams stream1 and stream2 individually. How can I do that cause as far as I know you cant readily copy a stream also even If I try to pipe original readStream to stream1, stream2 I cant consume each of them individually

like image 486
Mayank Patel Avatar asked Jul 23 '26 15:07

Mayank Patel


1 Answers

I found this docs in npmjs package docs

const fs = require("fs");
const ReadableStreamClone = require("readable-stream-clone");

const readStream = fs.createReadStream('text.txt');

const readStream1 = new ReadableStreamClone(readStream);
const readStream2 = new ReadableStreamClone(readStream);

const writeStream1 = fs.createWriteStream('sample1.txt');
const writeStream2 = fs.createWriteStream('sample2.txt');

readStream1.pipe(writeStream1)
readStream2.pipe(writeStream2)

try those line of code may be help you

like image 123
Kayes Fahim Avatar answered Jul 26 '26 06:07

Kayes Fahim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!