-
Notifications
You must be signed in to change notification settings - Fork 16
/
renderer.js
74 lines (57 loc) · 1.48 KB
/
renderer.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
71
72
73
74
var child_process = require('child_process');
var events = require('events');
var util = require('util');
var Renderer = module.exports = function(lApp, num) {
this.lApp = lApp;
this.workerNum = num || 1;
this.workers = [];
this.curWorker = 0;
};
util.inherits(Renderer, events.EventEmitter);
Renderer.prototype.init = function() {
var self = this;
function handler(task) {
var result = {};
// Convert string to json and html.
// For performance issue, we avoid using big json object between processes.
result.id = task.substr(0, 32);
if (task.substr(32, 1) == 'C') {
result.html = task.substr(33);
} else {
result.redirect = task.substr(33);
}
self.emit(result.id, result);
}
return function(done) {
// Starting workers
for (var index = 0; index < self.workerNum; index++) {
console.log('Starting renderer worker:', index);
var worker = child_process.fork(`${__dirname}/renderer_worker.js`);
worker.on('error', function(err) {
console.log(err);
});
worker.on('message', handler);
self.workers.push(worker);
}
done();
};
};
Renderer.prototype.render = function(data) {
var self = this;
return function(done) {
var worker = self.workers[self.curWorker++] || null;
if (!worker) {
self.curWorker = 1;
worker = self.workers[0];
}
var Utils = self.lApp.getLibrary('Utils');
var id = Utils.generateUniqueId();
self.once(id, function(result) {
done(null, result);
});
worker.send({
id: id,
data: data
});
};
};