-
Notifications
You must be signed in to change notification settings - Fork 7
/
stream-worker.js
95 lines (82 loc) · 2.28 KB
/
stream-worker.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
var Promise = require('bluebird');
/**
*
* @param {Stream} stream
* @param {Function} worker - work to be done on each data element of the stream
* @param {Object} options
* @param {Boolean} [options.promises=false] - if true, the worker operates using promises.
* @param {Number} [options.concurrency=10] - the maximum number of tasks to run concurrently
* @param {Function} [done] - if using callbacks, this is called when work on the stream finishes
*/
module.exports = function(stream, worker, options, done) {
var tasks = [],
running = 0,
closed = false,
firstError = null;
var promises = options.promises ? options.promises : false;
var concurrency = options.concurrency ? options.concurrency : 10;
if (promises === false) {
worker = Promise.promisify(worker);
}
return Promise.try(function() {
var resolve, reject;
var streamPromise = new Promise(function(__resolve, __reject) {
resolve = __resolve;
reject = __reject;
});
function errorHandler (err) {
if (err != null) {
if (firstError == null) {
firstError = err;
}
}
}
function closeHandler () {
closed = true;
completeIfDone();
}
function finishTask (err) {
running -= 1;
errorHandler(err);
if (tasks.length) {
startNextTask();
} else {
completeIfDone();
stream.resume();
}
}
function startNextTask () {
var data = tasks.shift();
if (data == null) {
completeIfDone();
}
running += 1;
Promise.try(function() { return worker(data); })
.then(function (finishedWith) {
finishTask();
return null;
}, function (err) {
finishTask(err);
return null;
});
}
function completeIfDone () {
if (!closed || tasks.length > 0 || running > 0) return;
if (firstError) return reject(firstError);
return resolve();
}
stream.on('data', function(data) {
tasks.push(data);
if (running < concurrency) {
startNextTask();
} else {
stream.pause();
}
});
stream.on('error', errorHandler);
stream.on('close', closeHandler);
stream.on('end', closeHandler);
return streamPromise;
})
.asCallback(done);
};