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);