Skip to content

Instantly share code, notes, and snippets.

@JbIPS
Created July 21, 2016 09:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JbIPS/60864ca74d4895ae42ca02ef1bdbe664 to your computer and use it in GitHub Desktop.
Save JbIPS/60864ca74d4895ae42ca02ef1bdbe664 to your computer and use it in GitHub Desktop.
Readable stream which concatenate multiples readable streams in Node.js
var Readable = require('stream').Readable
var util = require('util');
function ConcatStream(){
Readable.call(this);
this.streams = [];
}
util.inherits(ConcatStream, Readable);
ConcatStream.prototype.append = function(stream){
this.streams.push(stream);
stream.on('end', this.onEnd.bind(this));
stream.on('error', this.onError.bind(this));
}
ConcatStream.prototype._read = function(size){
var stream = this.streams[0];
stream.on('readable', function(){
var content;
while((content = stream.read(size)) != null){
this.push(content);
}
}.bind(this));
};
ConcatStream.prototype.onEnd = function() {
this.streams[0].removeAllListeners('end');
this.streams.shift();
if(this.streams.length == 0){
this.push(null);
}
else{
// You can uncomment this if you want to know when a new stream is being read
// this.emit('next');
this._read();
}
};
ConcatStream.prototype.onError = function(e){
this.emit('error', e);
this.onEnd();
}
// Example of use
var fs = require('fs');
var concat = new ConcatStream();
concat.append(fs.createReadStream('b.txt'));
concat.append(fs.createReadStream('c.txt'));
var str = concat.pipe(fs.createWriteStream('out.txt'));
concat.on('error', function(e){
console.log('error: ', e);
});
str.on('finish', function(){
console.log('finish of stream');
});
// out.txt will contains all of b.txt content, then all of c.txt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment