2016-11-03 01:33:53 +01:00
|
|
|
var Readable = require('readable-stream/readable');
|
|
|
|
var isReadable = require('is-stream').readable;
|
2016-10-10 03:43:44 +02:00
|
|
|
var util = require('util');
|
|
|
|
|
|
|
|
function addStream(streams, stream)
|
|
|
|
{
|
2016-11-03 01:33:53 +01:00
|
|
|
if(!isReadable(stream)) throw new Error('All input streams must be readable');
|
2016-10-10 03:43:44 +02:00
|
|
|
|
|
|
|
var self = this;
|
|
|
|
|
|
|
|
stream._buffer = [];
|
|
|
|
|
2016-11-03 01:33:53 +01:00
|
|
|
stream.on('readable', function()
|
2016-10-10 03:43:44 +02:00
|
|
|
{
|
2016-11-03 01:33:53 +01:00
|
|
|
var chunk = stream.read();
|
|
|
|
if (chunk === null)
|
|
|
|
return;
|
|
|
|
|
2016-10-10 03:43:44 +02:00
|
|
|
if(this === streams[0])
|
|
|
|
self.push(chunk);
|
|
|
|
|
|
|
|
else
|
|
|
|
this._buffer.push(chunk);
|
|
|
|
});
|
|
|
|
|
|
|
|
stream.on('end', function()
|
|
|
|
{
|
|
|
|
for(var stream = streams[0];
|
|
|
|
stream && stream._readableState.ended;
|
|
|
|
stream = streams[0])
|
|
|
|
{
|
|
|
|
while(stream._buffer.length)
|
|
|
|
self.push(stream._buffer.shift());
|
|
|
|
|
|
|
|
streams.shift();
|
|
|
|
}
|
|
|
|
|
|
|
|
if(!streams.length) self.push(null);
|
|
|
|
});
|
|
|
|
|
|
|
|
stream.on('error', this.emit.bind(this, 'error'));
|
|
|
|
|
|
|
|
streams.push(stream);
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
function OrderedStreams(streams, options) {
|
|
|
|
if (!(this instanceof(OrderedStreams))) {
|
|
|
|
return new OrderedStreams(streams, options);
|
|
|
|
}
|
|
|
|
|
|
|
|
streams = streams || [];
|
|
|
|
options = options || {};
|
|
|
|
|
|
|
|
options.objectMode = true;
|
|
|
|
|
|
|
|
Readable.call(this, options);
|
|
|
|
|
|
|
|
|
|
|
|
if(!Array.isArray(streams)) streams = [streams];
|
|
|
|
if(!streams.length) return this.push(null); // no streams, close
|
|
|
|
|
|
|
|
|
|
|
|
var addStream_bind = addStream.bind(this, []);
|
|
|
|
|
|
|
|
|
2016-11-03 01:33:53 +01:00
|
|
|
streams.forEach(function(item)
|
2016-10-10 03:43:44 +02:00
|
|
|
{
|
2016-11-03 01:33:53 +01:00
|
|
|
if(Array.isArray(item))
|
|
|
|
item.forEach(addStream_bind);
|
2016-10-10 03:43:44 +02:00
|
|
|
|
2016-11-03 01:33:53 +01:00
|
|
|
else
|
|
|
|
addStream_bind(item);
|
|
|
|
});
|
2016-10-10 03:43:44 +02:00
|
|
|
}
|
|
|
|
util.inherits(OrderedStreams, Readable);
|
|
|
|
|
|
|
|
OrderedStreams.prototype._read = function () {};
|
|
|
|
|
|
|
|
|
|
|
|
module.exports = OrderedStreams;
|