-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
126 lines (102 loc) · 2.2 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
var through2 = require('through2');
function trickleStream(size) {
return through2(function(chunk, encoding, callback) {
if(chunk && size && chunk.length > size) {
this.push(chunk.slice(0, size));
this._transform(chunk.slice(size, chunk.length), encoding, callback);
} else {
callback(null, chunk);
}
});
}
module.exports.trickle = trickleStream;
function delayStream(interval) {
var timestamp;
interval = interval || 0;
return through2(function(chunk, encoding, callback) {
var Self = this,
now = Date.now();
if(!timestamp) {
delay = interval;
} else {
if((now - timestamp) > interval) {
delay = interval;
} else {
delay = now - timestamp;
}
}
timestamp = now;
setTimeout(function() {
callback(null, chunk);
}, delay);
});
}
module.exports.delay = delayStream;
function combineStream(srcStream) {
if(!Array.isArray(srcStream)) {
srcStream = [srcStream];
}
var destStream = through2();
_flow(srcStream, destStream);
return destStream;
}
function _flow(srcs, dest) {
var src = srcs.shift();
if(!src) {
dest.end();
} else {
if(!src.readable) {
throw new Error('streams must be readable');
}
src.pipe(dest, {end: false});
src.on('end', function() {
_flow(srcs, dest);
});
}
}
module.exports.combine = combineStream;
function originStream(data) {
var stream = through2();
stream.write(data);
stream.end();
return stream;
}
module.exports.origin = originStream;
function aggreStream(comining) {
var stream = through2();
var buffer = [];
comining.on('data', function(chunk) {
buffer.push(chunk);
});
comining.on('end', function() {
buffer = Buffer.concat(buffer);
stream.end(buffer);
});
return stream;
}
module.exports.aggre = aggreStream;
function whenStream(streamArr, callback) {
if(!Array.isArray(streamArr)) {
streamArr = [streamArr];
}
var donelist = [];
var end = function() {
var isEnd = true;
donelist.forEach(function(value) {
if(!value) {
isEnd = false;
}
});
if(isEnd) {
callback && callback();
}
};
streamArr.forEach(function(stream, key) {
donelist[key] = false;
stream.on('end', function() {
donelist[key] = true;
end();
});
});
}
module.exports.when = whenStream;