Is there a way to duplicate or tee a Node.js readable stream so that the streams can be consumed independently from the same source?
My use case looks something like this:
f(inputStream, callback(err, data) {
// do stuff with data to change how g behaves
g(inputStream);
});
The requirement is that f
and g
start reading from the beginning of the stream. I would normally use readable.pipe
here but g
needs to happen in the callback.
You can pass the same readable stream to both f and g. They will read from the stream independent of one another.
For example:-
var fs = require('fs'); var str = fs.createReadStream('<file location>'); function f(s) { s.on('data', function (d) { console.log(d.toString()); }); s.on('end', function() { console.log('ended'); }); } function g(s) { s.on('data', function (d) { console.log(d.toString()); }); s.on('end', function() { console.log('ended'); }); } g(str); f(str);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.