-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstreams-end.js
48 lines (36 loc) · 1.02 KB
/
streams-end.js
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
var eos = require('end-of-stream')
var once = require('once')
module.exports = StreamsEnd
function StreamsEnd (streams, callback) {
if (!(this instanceof StreamsEnd)) return new StreamsEnd(streams, callback)
if (typeof streams === 'function') {
callback = streams
streams = []
}
this._streams = streams || []
this._endedCount = 0
this.setCallback(callback)
}
StreamsEnd.prototype.push = function (stream) {
var self = this
var callback = this._callback
var attemptEnd = this.attemptEnd
this._streams.push(stream)
eos(stream, function (err) {
if (err) return callback(err)
self._endedCount++
attemptEnd.call(self)
})
}
StreamsEnd.prototype.setCallback = function (callback) {
this._callback = callback ? once(callback) : undefined
if (this._callback) this.attemptEnd()
}
StreamsEnd.prototype.attemptEnd = function () {
if (this._callback && this.ended()) {
return this._callback()
}
}
StreamsEnd.prototype.ended = function () {
return this._endedCount === this._streams.length
}