From b5f1f1532ed12f8b675a537b7b46222562d8e95f Mon Sep 17 00:00:00 2001 From: Failattu Date: Fri, 18 Sep 2015 15:49:14 +0300 Subject: [PATCH] FIXED issue #1 so that Node.JS will run in a multiple threads --- server.js | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/server.js b/server.js index 2563513..de8880c 100644 --- a/server.js +++ b/server.js @@ -2,9 +2,28 @@ var morgan = require('morgan'); var server = require('./app'); +var cluster = require('cluster'); + var port = process.env.PORT || 8080; +var workers = require('os').cpus().length server.use(morgan('dev', {immediate: true})); -server.listen(port); +// Clustering to utilize all CPU cores +if (cluster.isMaster) { + + // Fork workers + for (var i = 0; i < workers; i++) { + cluster.fork(); + } + + cluster.on('exit', function (worker, code, signal) { + console.log('Worker ' + worker.process.pid + ' died'); + console.log('Spawining new worker...'); + cluster.fork(); + }); +} +else { + server.listen(port); +} console.log("App listening on port " + port);