This repository has been archived by the owner on Apr 5, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
83 lines (64 loc) · 1.64 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
80
81
82
83
var Stream = require('stream').Stream
, util = require('util')
var instance = 0
function SlowStream (options) {
this.instance = instance++
Stream.call(this)
this.options = options
this.writable = true
this.readable = true
this.queue = []
this._lastWrite = process.hrtime()
this._timeout = null
this._ended = false
this._paused = false
}
util.inherits(SlowStream, Stream)
SlowStream.prototype.write = function write (data) {
this.queue.push(data)
this.flush()
return this.queue.length === 0
}
SlowStream.prototype.resume = function resume () {
this._paused = false
this.flush()
}
SlowStream.prototype.pause = function pause () {
this._paused = true
}
SlowStream.prototype.flush = function flush () {
var interval = process.hrtime(this._lastWrite)
, gap = interval[1] / 1000000 - this.options.maxWriteInterval
if (this._paused) return
if (this.queue.length) {
if (gap >= 0) {
this.emit('data', this.queue.shift())
this._lastWrite = process.hrtime()
}
if (!this._timeout) {
this._timeout = setTimeout(function () {
this._timeout = null
this.flush()
}.bind(this), gap < 0 ? -gap : this.options.maxWriteInterval)
}
} else if (this._ended) {
if (!this._closed) {
this._closed = true
this.emit('end')
this.emit('close')
}
} else {
this.emit('drain')
}
}
SlowStream.prototype.end = function end () {
this._ended = true
this.flush()
}
SlowStream.prototype.destroySoon = function destroySoon () {
this.end()
}
SlowStream.prototype.destroy = function destroy () {
this.end()
}
module.exports = SlowStream