oc-mux-demux
Version:
Multiplexing-demultiplexing of several object streams inside single object
61 lines (51 loc) • 1.28 kB
JavaScript
// Generated by CoffeeScript 1.9.0
/*
Multiplexing-demultiplexing of several object streams inside single object
stream.
*/
(function() {
var through;
through = require('through2');
module.exports = function(options) {
var s;
if (options == null) {
options = {};
}
/*
Create mux-demux stream.
:param options: Object with options
:option error: Propagate error on substreams (default ``false``)
*/
s = through.obj(function(chunk, enc, cb) {
var name, pos, ss;
pos = chunk.indexOf('|');
name = chunk.substring(0, pos);
chunk = chunk.substring(++pos);
ss = s.streams[name];
if (!ss) {
console.warn("orphaned data for stream " + name);
} else {
ss.push(chunk);
}
return cb();
});
s.streams = {};
s.createStream = function(name) {
var ss;
ss = s.streams[name] = through.obj(function(chunk, enc, cb) {
s.push(name + "|" + chunk);
return cb();
});
s.on('end', function() {
return ss.emit('end');
});
if (options.error) {
s.on('error', function() {
return ss.emit('error');
});
}
return ss;
};
return s;
};
}).call(this);