-
Notifications
You must be signed in to change notification settings - Fork 10
/
nodeWorkerUtils.js
64 lines (57 loc) · 1.88 KB
/
nodeWorkerUtils.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
var JSONStreamParser = require('./lib/JSONStreamParser');
var util = require('util');
function respondWithError(err) {
if (util.isError(err)) {
err = err.stack;
}
console.log(JSON.stringify({error: err}, null, 2));
}
function respondWithResult(result) {
console.log(JSON.stringify({response: result}, null, 2));
}
function startWorker(onInitialize, onMessageReceived, onShutdown) {
process.stdin.resume();
process.stdin.setEncoding('utf8');
var inputStreamParser = new JSONStreamParser();
var initialized = false;
var initData = null;
process.stdin.on('data', function(data) {
var rcvdMsg = inputStreamParser.parse(data);
if (rcvdMsg.length === 1) {
if (initialized === false) {
try {
onInitialize && onInitialize(rcvdMsg[0].initData);
initialized = true;
console.log(JSON.stringify({initSuccess: true}));
} catch (e) {
console.log(JSON.stringify({initError: e.stack || e.message}));
throw e;
}
} else {
try {
var message = rcvdMsg[0].message;
onMessageReceived(message).then(function(response) {
if (!response || typeof response !== 'object') {
throw new Error(
'Invalid response returned by worker function: ' +
JSON.stringify(response, null, 2)
);
}
return response;
}).then(respondWithResult, respondWithError);
} catch (e) {
respondWithError(e.stack || e.message);
}
}
} else if (rcvdMsg.length > 1) {
throw new Error(
'Received multiple messages at once! Not sure what to do, so bailing ' +
'out!'
);
}
});
onShutdown && process.stdin.on('end', onShutdown);
}
exports.respondWithError = respondWithError;
exports.respondWithResult = respondWithResult;
exports.startWorker = startWorker;