-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfork.js
58 lines (47 loc) · 1.22 KB
/
fork.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
'use strict';
var fork = require('child_process').fork;
var path = require('path');
/**
* @param func
*/
module.exports = function (func) {
var thread = fork(path.join(__dirname, 'worker.js'));
thread.send({
type: 'function',
data: func.toString()
});
thread.resultHandler = thread.errorHandler = thread.exitHandler = function () {};
thread.sendData = function (data) {
this.send({
type: 'input',
data: data
});
return this;
};
thread.onResult = function (handler) {
this.resultHandler = handler;
return this;
};
thread.onError = function (handler) {
this.errorHandler = handler;
return this;
};
thread.onExit = function (handler) {
this.exitHandler = handler;
return this;
};
thread.on('message', function (message) {
switch (message.type) {
case 'result':
this.resultHandler(message.data);
break;
case 'error':
this.errorHandler(message.data);
break;
default:
// ...
}
});
thread.on('exit', thread.exitHandler);
return thread;
};