Setting up a Node.js Cluster
var cluster = require('cluster'); var numCPUs = require('os').cpus().length; if (cluster.isMaster) { // Fork workers. for (var i = 0; i < numCPUs; i++) { cluster.fork(); } Object.keys(cluster.workers).forEach(function(id) { console.log("I am running with ID : "+cluster.workers[id].process.pid); }); cluster.on('exit', function(worker, code, signal) { console.log('worker ' + worker.process.pid + ' died'); }); } else { //Do further processing. }
Express :
app.js
var express=require("express"); var app=express(); app.get('/',function(req,res){ res.end("Hello world !"); }); app.listen(3000,function(){ console.log("Running at PORT 3000"); });
cluster.js
var cluster = require('cluster'); var numCPUs = require('os').cpus().length; if (cluster.isMaster) { for (var i = 0; i < numCPUs; i++) { cluster.fork(); } cluster.on('exit', function(worker, code, signal) { console.log('worker ' + worker.process.pid + ' died'); }); } else { //change this line to Your Node.js app entry point. require("./app.js"); }
References
https://codequs.com/p/BkCZ1VMY/setting-up-a-node-js-cluster/
https://www.sitepoint.com/how-to-create-a-node-js-cluster-for-speeding-up-your-apps/
https://nodejs.org/api/cluster.html