2016-04-15 06:22:04 +02:00
|
|
|
const through = require('through2')
|
|
|
|
|
|
|
|
module.exports = ObjectMultiplex
|
|
|
|
|
2016-06-21 22:18:32 +02:00
|
|
|
function ObjectMultiplex (opts) {
|
2016-04-15 06:22:04 +02:00
|
|
|
opts = opts || {}
|
|
|
|
// create multiplexer
|
2017-08-02 23:25:28 +02:00
|
|
|
const mx = through.obj(function (chunk, enc, cb) {
|
|
|
|
const name = chunk.name
|
|
|
|
const data = chunk.data
|
|
|
|
if (!name) {
|
|
|
|
console.warn(`ObjectMultiplex - Malformed chunk without name "${chunk}"`)
|
|
|
|
return cb()
|
|
|
|
}
|
|
|
|
const substream = mx.streams[name]
|
2016-04-15 06:22:04 +02:00
|
|
|
if (!substream) {
|
2017-08-02 23:25:28 +02:00
|
|
|
console.warn(`ObjectMultiplex - orphaned data for stream "${name}"`)
|
2016-04-15 06:22:04 +02:00
|
|
|
} else {
|
2016-10-12 21:35:55 +02:00
|
|
|
if (substream.push) substream.push(data)
|
2016-04-15 06:22:04 +02:00
|
|
|
}
|
|
|
|
return cb()
|
|
|
|
})
|
|
|
|
mx.streams = {}
|
|
|
|
// create substreams
|
2016-06-21 22:18:32 +02:00
|
|
|
mx.createStream = function (name) {
|
2017-08-02 23:25:28 +02:00
|
|
|
const substream = mx.streams[name] = through.obj(function (chunk, enc, cb) {
|
2016-04-15 06:22:04 +02:00
|
|
|
mx.push({
|
|
|
|
name: name,
|
|
|
|
data: chunk,
|
|
|
|
})
|
|
|
|
return cb()
|
|
|
|
})
|
2016-06-21 22:18:32 +02:00
|
|
|
mx.on('end', function () {
|
2016-04-15 06:22:04 +02:00
|
|
|
return substream.emit('end')
|
|
|
|
})
|
|
|
|
if (opts.error) {
|
2016-06-21 22:18:32 +02:00
|
|
|
mx.on('error', function () {
|
2016-04-15 06:22:04 +02:00
|
|
|
return substream.emit('error')
|
|
|
|
})
|
|
|
|
}
|
|
|
|
return substream
|
|
|
|
}
|
2016-10-12 21:35:55 +02:00
|
|
|
// ignore streams (dont display orphaned data warning)
|
|
|
|
mx.ignoreStream = function (name) {
|
|
|
|
mx.streams[name] = true
|
|
|
|
}
|
2016-04-15 06:22:04 +02:00
|
|
|
return mx
|
|
|
|
}
|