UNPKG

3.15 kBJavaScriptView Raw
1// Change the current working directory to ensure that files are relative to the current directory.
2process.chdir(__dirname);
3
4// Module dependencies
5var cluster = require('cluster');
6require('colors');
7require('string-format');
8
9var settings = require('./config/settings'); // the configuration settings have been initialized
10
11var createMaster = function(cluster) {
12 console.log('Starting directory:', process.cwd());
13 console.log('NodeJS-%s-%s-%s', process.version, process.platform, process.arch);
14
15 // Fork workers
16 for (var i = 0; i < settings.cluster.maxWorkers; ++i) {
17 cluster.fork();
18 }
19
20 // Event: online
21 cluster.on('online', function(worker) {
22 console.log('The worker #%d(pid=%d) is online', worker.id, worker.process.pid);
23 });
24
25 // Event: listening
26 cluster.on('listening', function(worker, address) {
27 console.log('The worker #%d(pid=%d) is listening on ' + '%s:%d'.bold.red, worker.id, worker.process.pid, address.address, address.port);
28 });
29
30 // Event: disconnect
31 cluster.on('disconnect', function(worker) {
32 console.log('The worker #%d(pid=%d) has disconnected', worker.id, worker.process.pid);
33 });
34
35 // Event: exit
36 cluster.on('exit', function(worker, code, signal) {
37 var exitCode = worker.process.exitCode;
38 console.log('The worker #%d(pid=%d) died (%d). restarting...', worker.id, worker.process.pid, exitCode);
39 cluster.fork();
40 });
41};
42
43var createServer = function() {
44 var app = require('./app')();
45 var server = require('http').createServer(app);
46
47 server.setMaxListeners(0); // Set to zero for unlimited
48
49 server.listen(settings.port, function() {
50 // Lower the process privileges by setting the UID and GUID after the process has mound to the port.
51 if (settings.uid) {
52 process.setuid(settings.uid);
53 }
54 if (settings.gid) {
55 process.setgid(settings.gid);
56 }
57 var address = server.address();
58 console.log('Server is listening on %s:%d', address.address, address.port);
59 });
60};
61
62if (settings.cluster.enable) {
63 if (cluster.isMaster) { // True if the process is a master.
64 createMaster(cluster);
65
66 // Event: message
67 Object.keys(cluster.workers).forEach(function(id) {
68 cluster.workers[id].on('message', function(msg) {
69 if (msg.cmd === 'bonjour') {
70 console.log('Received a bonjour command from worker #%d(pid=%d)', this.id, this.process.pid);
71 this.send({reply: 'ok'});
72 }
73 });
74 });
75
76 } else if (cluster.isWorker) { // True if the process is not a master (it is the negation of cluster.isMaster).
77 createServer();
78
79 // Event: message
80 process.send({cmd: 'bonjour'});
81 process.on('message', function(msg) {
82 console.log('Received a bonjour reply from master: %s', JSON.stringify(msg));
83 });
84 }
85} else {
86 // Debugging Clustered Apps with Node-Inspector
87 // http://strongloop.com/strongblog/whats-new-nodejs-v0-12-debugging-clusters/
88 createServer();
89}