-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
master.js
70 lines (63 loc) · 1.48 KB
/
master.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
/**
* Master of child processes. Handles communication between the
* processor and the main process.
*
*/
var status;
var processor;
var Promise = require('bluebird');
// https://stackoverflow.com/questions/18391212/is-it-not-possible-to-stringify-an-error-using-json-stringify
if (!('toJSON' in Error.prototype)){
Object.defineProperty(Error.prototype, 'toJSON', {
value: function () {
var alt = {};
Object.getOwnPropertyNames(this).forEach(function (key) {
alt[key] = this[key];
}, this);
return alt;
},
configurable: true,
writable: true
});
}
process.on('message', function(msg) {
switch(msg.cmd){
case 'init':
processor = require(msg.value);
status = 'IDLE';
break;
case 'start':
if(status !== 'IDLE'){
return process.send({
cmd: 'error',
err: new Error('cannot start a not idling child process')
});
}
status = 'STARTED';
Promise.resolve(processor(wrapJob(msg.job)) || {}).then( function(result) {
process.send({
cmd: 'completed',
value: result
});
}, function(err) {
process.send({
cmd: 'failed',
value: err
});
}).finally(function(){
status = 'IDLE';
});
break;
case 'stop':
break;
}
});
function wrapJob(job){
job.progress = function(progress){
process.send({
cmd: 'progress',
value: progress
});
};
return job;
}