-
Notifications
You must be signed in to change notification settings - Fork 24
/
dataStream.js
49 lines (41 loc) · 887 Bytes
/
dataStream.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
const EventEmitter = require('events')
class DataStream extends EventEmitter {
constructor () {
super()
// Declares
this._chunks = []
this.listeners = 0
this.isEnded = false
// Bindings
this.tick = this.tick.bind(this)
this.write = this.write.bind(this)
this.end = this.end.bind(this)
// Init
this.tick()
}
tick () {
var hasData = this._chunks.length !== 0
while (this._chunks.length) {
const chunk = this._chunks.shift()
this.emit('data', chunk)
}
if (hasData && this._chunks.length === 0) {
this.emit('empty')
}
if (!this.isEnded) {
setTimeout(() => {
this.tick()
}, 100)
}
}
write (chunck) {
this._chunks.push(chunck)
}
end () {
process.nextTick(() => {
this.isEnded = true
this.emit('end')
})
}
}
module.exports = DataStream