heyujie
2021-06-07 8f8155aa4c83f7c2577ac123add550766b6a7ce3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
var Readable = require('readable-stream/readable');
var util = require('util');
 
function isReadable(stream) {
  if (typeof stream.pipe !== 'function') {
    return false;
  }
 
  if (!stream.readable) {
    return false;
  }
 
  if (typeof stream._read !== 'function') {
    return false;
  }
 
  if (!stream._readableState) {
    return false;
  }
 
  return true;
}
 
function addStream (streams, stream) {
  if (!isReadable(stream)) {
    throw new Error('All input streams must be readable');
  }
 
  var self = this;
 
  stream._buffer = [];
 
  stream.on('readable', function () {
    var chunk = stream.read();
    while (chunk) {
      if (this === streams[0]) {
        self.push(chunk);
      } else {
        this._buffer.push(chunk);
      }
      chunk = stream.read();
    }
  });
 
  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 addStreamBinded = addStream.bind(this, []);
 
  streams.forEach(function (item) {
    if (Array.isArray(item)) {
      item.forEach(addStreamBinded);
    } else {
      addStreamBinded(item);
    }
  });
}
util.inherits(OrderedStreams, Readable);
 
OrderedStreams.prototype._read = function () {};
 
module.exports = OrderedStreams;