Created
January 22, 2015 18:29
-
-
Save jpillora/b098fa5a5d1db10ee0d8 to your computer and use it in GitHub Desktop.
Through stream
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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