-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
66 lines (55 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
'use strict';
const { EventEmitter } = require('events');
const fg = require('fast-glob');
const workerFarm = require('worker-farm');
class FileProcessor extends EventEmitter {
constructor(globPattern, worker, options = {}, globOptions = {}) {
super();
options = options || {};
const glob = (this.glob = fg.stream(globPattern, globOptions));
this.invokeWorker = options.invokeWorker || defaultInvokeWorker;
const workers = (this.workers = workerFarm(options.worker || {}, worker));
let allQueued = false;
let errorHappened = false;
let queuedCount = 0;
let processedCount = 0;
const checkForEnd = () => {
if (errorHappened || (allQueued && queuedCount === processedCount)) {
if (!options.keepAlive) {
workerFarm.end(workers);
}
if (!errorHappened) this.emit('end');
}
};
glob.on('data', (path) => {
queuedCount++;
this.emit('queued', path);
this.process(path, (err, result) => {
processedCount++;
if (err) {
errorHappened = true;
this.emit('error', err);
} else {
this.emit('processed', path, result);
}
checkForEnd();
});
});
glob.on('end', () => {
allQueued = true;
this.emit('allQueued', { queuedCount, processedCount });
checkForEnd();
});
}
process(path, callback) {
this.invokeWorker(this.workers, path, callback);
}
destroy(callback) {
this.glob.destroy();
workerFarm.end(this.workers, callback);
}
}
function defaultInvokeWorker(workers, path, callback) {
workers(path, callback);
}
module.exports = FileProcessor;