nifty-wallet/app/scripts/lib/obj-multiplex.js

45 lines
1.0 KiB
JavaScript
Raw Normal View History

2016-04-14 21:22:04 -07:00
const through = require('through2')
module.exports = ObjectMultiplex
2016-06-21 13:18:32 -07:00
function ObjectMultiplex (opts) {
2016-04-14 21:22:04 -07:00
opts = opts || {}
// create multiplexer
2016-06-21 13:18:32 -07:00
var mx = through.obj(function (chunk, enc, cb) {
2016-04-14 21:22:04 -07:00
var name = chunk.name
var data = chunk.data
var substream = mx.streams[name]
if (!substream) {
console.warn(`orphaned data for stream "${name}"`)
2016-04-14 21:22:04 -07:00
} else {
if (substream.push) substream.push(data)
2016-04-14 21:22:04 -07:00
}
return cb()
})
mx.streams = {}
// create substreams
2016-06-21 13:18:32 -07:00
mx.createStream = function (name) {
var substream = mx.streams[name] = through.obj(function (chunk, enc, cb) {
2016-04-14 21:22:04 -07:00
mx.push({
name: name,
data: chunk,
})
return cb()
})
2016-06-21 13:18:32 -07:00
mx.on('end', function () {
2016-04-14 21:22:04 -07:00
return substream.emit('end')
})
if (opts.error) {
2016-06-21 13:18:32 -07:00
mx.on('error', function () {
2016-04-14 21:22:04 -07:00
return substream.emit('error')
})
}
return substream
}
// ignore streams (dont display orphaned data warning)
mx.ignoreStream = function (name) {
mx.streams[name] = true
}
2016-04-14 21:22:04 -07:00
return mx
}