Skip to content

Instantly share code, notes, and snippets.

@devarajchidambaram
Created February 2, 2018 05:46
Show Gist options
  • Save devarajchidambaram/55f9dcd5a27d1e2cf550b89d1e9e6d8e to your computer and use it in GitHub Desktop.
Save devarajchidambaram/55f9dcd5a27d1e2cf550b89d1e9e6d8e to your computer and use it in GitHub Desktop.
Nodejs cluster up the worker process if it fails
var http = require('http');
var cluster = require('cluster');
// The master's job to spawn workers initially and when they die
if (cluster.isMaster) {
// Get the number of processor cores
var cpuCount = require('os').cpus().length;
// Create a worker for each CPU
for (var i = 0; i < cpuCount; i += 1) {
cluster.fork();
} // When a worker exits, fork a new one
cluster.on('exit', function(worker) {
console.log('Worker %d died', worker.id);
cluster.fork();
});
} else if (cluster.isWorker) {
// The real work here for the worker
http.createServer(function(request, response) {
console.log('Ready to accept request');
// This will cause the server to crash
var i = n.start;
response.writeHead(200, {
'Content-Type': 'text/plain',
'Access-Control-Allow-Origin': '*'
});
response.end('Hello World\n');
}).listen(1337);
// Exit the process when there is an uncaught exception
console.log('Worker %d running!', cluster.worker.id);
process.on('uncaughtException', function() {
console.log('Handled the exception here');
process.exit(1);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment