-
Notifications
You must be signed in to change notification settings - Fork 1
/
worker_wrapper.js
49 lines (45 loc) · 1.16 KB
/
worker_wrapper.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
var vm = require('vm');
var sys = require('sys');
var lcUtils = require(__dirname + '/utils');
var createExtendedEmitter = lcUtils.createExtendedEmitter;
var objectToArray = lcUtils.objectToArray;
var events;
var startWorker = function(message) {
var workerFun;
var workerFromCode = function(workerCode) {
try {
var sandbox = {tempFun: null};
vm.runInNewContext('tempFun = ' + workerCode, sandbox, 'worker_instance.js');
return sandbox.tempFun;
} catch(e) {
sys.debug(e);
}
};
var workerFromFile = function(workerPath) {
return require(workerPath);
}
if(message.workerCode) {
workerFun = workerFromCode(message.workerCode);
} else {
workerFun = workerFromFile(message.workerPath);
}
events = createExtendedEmitter();
events.onAll(function() {
postMessage({arguments: objectToArray(arguments)});
});
workerFun(events);
};
onmessage = function(e) {
var message = e.data;
if(!events) {
startWorker(message);
} else {
events.constructor.prototype.emit.apply(events, message.arguments);
}
};
onclose = function() {
sys.debug('Worker shutting down.');
if(events) {
events.emit('close');
}
};