Skip to content

Instantly share code, notes, and snippets.

@jpillora
Created January 22, 2015 18:29
Show Gist options
  • Save jpillora/b098fa5a5d1db10ee0d8 to your computer and use it in GitHub Desktop.
Save jpillora/b098fa5a5d1db10ee0d8 to your computer and use it in GitHub Desktop.
Through stream
var stream = require('stream');
var Transform = stream.Transform;
module.exports = function through(opts, transform, flush) {
//use default options
if (typeof opts !== 'object') {
flush = transform;
transform = opts;
opts = {
objectMode: true
};
}
//always allow objects
var t = new Transform(opts);
//depending on transform fn arity, pass in diff args
t._transform =
typeof transform !== 'function' ? function throughzero(data, enc, next) {
next(null, data);
} :
transform.length === 3 ? transform :
transform.length === 2 ? function throughtwo(obj, enc, next) {
transform.call(this, obj, next);
} :
transform.length === 1 ? function throughone(obj, enc, next) {
transform.call(this, obj);
next();
} :
null;
//give stream objects names
if (transform && transform.name)
t.name = transform.name;
t._flush = flush;
return t;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment