Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80635 views
1
var JSONStreamParser = require('./lib/JSONStreamParser');
2
var Q = require('q');
3
var util = require('util');
4
5
function respondWithError(err) {
6
if (util.isError(err)) {
7
err = err.stack;
8
}
9
console.log(JSON.stringify({error: err}, null, 2));
10
}
11
12
function respondWithResult(result) {
13
console.log(JSON.stringify({response: result}, null, 2));
14
}
15
16
function startWorker(onInitialize, onMessageReceived, onShutdown) {
17
process.stdin.resume();
18
process.stdin.setEncoding('utf8');
19
var inputStreamParser = new JSONStreamParser();
20
21
var initialized = false;
22
var initData = null;
23
24
process.stdin.on('data', function(data) {
25
var rcvdMsg = inputStreamParser.parse(data);
26
if (rcvdMsg.length === 1) {
27
if (initialized === false) {
28
try {
29
onInitialize && onInitialize(rcvdMsg[0].initData);
30
initialized = true;
31
console.log(JSON.stringify({initSuccess: true}));
32
} catch (e) {
33
console.log(JSON.stringify({initError: e.stack || e.message}));
34
throw e;
35
}
36
} else {
37
try {
38
var message = rcvdMsg[0].message;
39
onMessageReceived(message).then(function(response) {
40
if (!response || typeof response !== 'object') {
41
throw new Error(
42
'Invalid response returned by worker function: ' +
43
JSON.stringify(response, null, 2)
44
);
45
}
46
return response;
47
}).done(respondWithResult, respondWithError);
48
} catch (e) {
49
respondWithError(e.stack || e.message);
50
}
51
}
52
} else if (rcvdMsg.length > 1) {
53
throw new Error(
54
'Received multiple messages at once! Not sure what to do, so bailing ' +
55
'out!'
56
);
57
}
58
});
59
60
onShutdown && process.stdin.on('end', onShutdown);
61
}
62
63
exports.respondWithError = respondWithError;
64
exports.respondWithResult = respondWithResult;
65
exports.startWorker = startWorker;
66
67