@seeessence/stream
Version:
Two-way duplex stream
63 lines (47 loc) • 1.8 kB
JavaScript
var EventEmitter = require('events').EventEmitter;
var PassThrough = require('stream').PassThrough;
var debug = require('./debug.js');
module.exports = function (arterial, venous, name) {
var stream = new EventEmitter();
if (arterial instanceof Function || typeof arterial === 'function') {
arterial = (function (arterial) {
return new PassThrough({
objectMode: true,
transform: function(object, encoding, callback) {
arterial(object, callback.bind(null));
}
});
})(arterial);
}
if (venous instanceof Function || typeof venous === 'function') {
venous = (function (venous) {
return new PassThrough({
objectMode: true,
transform: function(object, encoding, callback) {
venous(object, callback.bind(null));
}
});
})(venous);
}
process.env.npm_package_config_debug && debug(arterial, name, arguments.callee);
process.env.npm_package_config_debug && debug(venous, name, arguments.callee);
stream.pipe = function () {
for (var argument in arguments)
if (arguments.hasOwnProperty(argument))
arterial.pipe(arguments[argument], {end: false});
return stream;
};
var emit = true;
arterial.on('pipe', function (source) {
emit && source.unpipe(this);
emit && source.pipe(venous);
emit = true;
});
stream.on('pipe', function (source) {
source.unpipe(this);
emit = false;
source.pipe(arterial);
venous.pipe(source);
});
return stream;
};