forked from dominictarr/through
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
80 lines (74 loc) · 1.92 KB
/
index.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
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
var Stream = require('stream')
// through
//
// a stream that does nothing but re-emit the input.
// useful for aggregating a series of changing but not ending streams into one stream)
exports = module.exports = through
through.through = through
//create a readable writable stream.
function through (write, end) {
write = write || function (data) { this.emit('data', data) }
end = (
'sync'== end || !end
//use sync end. (default)
? function () { this.emit('end') }
: 'async' == end || end === true
//use async end.
//must eventually call drain if paused.
//else will not end.
? function () {
if(!this.paused)
return this.emit('end')
var self = this
this.once('drain', function () {
self.emit('end')
})
}
//use custom end function
: end
)
var ended = false, destroyed = false
var stream = new Stream()
stream.readable = stream.writable = true
stream.paused = false
stream.write = function (data) {
write.call(this, data)
return !stream.paused
}
//this will be registered as the first 'end' listener
//must call destroy next tick, to make sure we're after any
//stream piped from here.
stream.on('end', function () {
stream.readable = false
if(!stream.writable)
process.nextTick(function () {
stream.destroy()
})
})
stream.end = function (data) {
if(ended) throw new Error('cannot call end twice')
ended = true
if(arguments.length) stream.write(data)
this.writable = false
end.call(this)
if(!this.readable)
this.destroy()
}
stream.destroy = function () {
if(destroyed) return
destroyed = true
ended = true
stream.writable = stream.readable = false
stream.emit('close')
}
stream.pause = function () {
stream.paused = true
}
stream.resume = function () {
if(stream.paused) {
stream.paused = false
stream.emit('drain')
}
}
return stream
}