Skip to content

Instantly share code, notes, and snippets.

@sivasankars
Created June 2, 2018 06:59
Show Gist options
  • Save sivasankars/46ed13b7423f088a1d78c7fd16731e7a to your computer and use it in GitHub Desktop.
Save sivasankars/46ed13b7423f088a1d78c7fd16731e7a to your computer and use it in GitHub Desktop.
Node.js Cluster With Express.js. More @ http://niralar.com/nodejs-cluster-with-expressjs/
const express = require('express');
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
// Fork workers.
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`);
cluster.fork(); // Create a New Worker, If Worker is Dead
});
} else {
const app = express();
app.get('/', (req, res) => res.send('Hello World!' + cluster.worker.id));
http.createServer(app).listen(3000, function () {
console.log("Express server listening on port 3000 as Worker " + cluster.worker.id + " running @ process " + cluster.worker.process.pid + "!");
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment