-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
77 lines (59 loc) · 1.62 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
var Transform = require('readable-stream/transform');
var util = require('util');
var reduce = require('lodash.reduce');
function ChunkyStream (options) {
if (!(this instanceof ChunkyStream)) {
return new ChunkyStream(options);
}
options.objectMode = true;
options.writeableObjectMode = true;
options.readableObjectMode = true;
this.ignoreEmpty = options.ignoreEmpty;
this.interval = options.interval;
this.timeoutId = null;
this.chunks = [];
this.conditions = [];
Transform.call(this, options);
}
util.inherits(ChunkyStream, Transform);
ChunkyStream.prototype.use = function (condition) {
this.conditions.push(condition);
};
ChunkyStream.prototype.flush = function () {
if (this.chunks.length === 0) {
return;
}
this.push(this.chunks);
this.chunks = [];
};
ChunkyStream.prototype.disableTimeout = function () {
if (this.timeoutId) {
clearTimeout(this.timeoutId);
this.timeoutId = null;
}
};
ChunkyStream.prototype.enableTimeout = function () {
if (this.interval > 0) {
this.timeoutId = setTimeout(this.flush.bind(this), this.interval);
}
};
ChunkyStream.prototype._transform = function (chunk, encoding, callback) {
this.disableTimeout();
var chunks = this.chunks;
var flush = reduce(this.conditions, function (value, condition) {
return value || condition(chunks, chunk);
}, false);
if (flush) {
this.flush();
}
if (!this.ignoreEmpty || (chunk && chunk.length > 0)) {
this.chunks.push(chunk);
}
this.enableTimeout();
callback();
};
ChunkyStream.prototype._flush = function (callback) {
this.flush();
callback();
};
module.exports = ChunkyStream;