Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80540 views
1
var duplexer = require('duplexer2')
2
var through = require('through2')
3
4
module.exports = function () {
5
var streams
6
if(arguments.length == 1 && Array.isArray(arguments[0])) {
7
streams = arguments[0]
8
} else {
9
streams = [].slice.call(arguments)
10
}
11
return combine(streams)
12
}
13
14
module.exports.obj = function () {
15
var streams
16
if(arguments.length == 1 && Array.isArray(arguments[0])) {
17
streams = arguments[0]
18
} else {
19
streams = [].slice.call(arguments)
20
}
21
return combine(streams, { objectMode: true })
22
}
23
24
25
function combine (streams, opts) {
26
27
for (var i = 0; i < streams.length; i++)
28
streams[i] = wrap(streams[i], opts)
29
30
if(streams.length == 0)
31
return through(opts)
32
else if(streams.length == 1)
33
return streams[0]
34
35
var first = streams[0]
36
, last = streams[streams.length - 1]
37
, thepipe = duplexer(first, last)
38
39
//pipe all the streams together
40
41
function recurse (streams) {
42
if(streams.length < 2)
43
return
44
streams[0].pipe(streams[1])
45
recurse(streams.slice(1))
46
}
47
48
recurse(streams)
49
50
function onerror () {
51
var args = [].slice.call(arguments)
52
args.unshift('error')
53
thepipe.emit.apply(thepipe, args)
54
}
55
56
//es.duplex already reemits the error from the first and last stream.
57
//add a listener for the inner streams in the pipeline.
58
for(var i = 1; i < streams.length - 1; i ++)
59
streams[i].on('error', onerror)
60
61
return thepipe
62
}
63
64
function wrap (tr, opts) {
65
if (typeof tr.read === 'function') return tr
66
if (!opts) opts = tr._options || {}
67
var input = through(opts), output = through(opts)
68
input.pipe(tr).pipe(output)
69
var dup = duplexer(input, output)
70
tr.on('error', function (err) { dup.emit('error', err) });
71
return dup;
72
}
73
74