Skip to content

Instantly share code, notes, and snippets.

@jpillora
Created May 5, 2014 01:56
Show Gist options
  • Save jpillora/c41ce28b4c8fb11d0427 to your computer and use it in GitHub Desktop.
Save jpillora/c41ce28b4c8fb11d0427 to your computer and use it in GitHub Desktop.
Combine 'through' streams
// combine an existing pipeline:
// entry -> s1 -> s2 -> s3 -> s4 -> exit
// into:
// P
// where sX -> P => sX -> entry
// and P -> sY => exit -> sY
var combine = function(entry, exit) {
//simple proxy stream
var combination = through();
// -> exit -> combination ->
exit.pipe(combination);
// combination -> entry ->
// further attempts to pipe to combination
// will actually pipe to entry
combination.on('pipe', function(s) {
s.unpipe(combination);
s.pipe(entry);
});
return combination;
};
//where 'through' is a basic transform stream helper
var Transform = require('stream').Transform;
var through = function through(transform, flush) {
//always allow objects
var t = new Transform({ objectMode: true });
t._transform = transform || function(data, enc, next) {
next(null, data);
};
t._flush = flush;
return t;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment