Skip to content

Instantly share code, notes, and snippets.

@hlfshell
Last active May 3, 2017 15:04
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hlfshell/2e6e15e497b9000983d63083c7c68a9f to your computer and use it in GitHub Desktop.
Save hlfshell/2e6e15e497b9000983d63083c7c68a9f to your computer and use it in GitHub Desktop.
const cluster = require('cluster');
const childProcess = require('child_process');
const cpus = require('os').cpus().length;
const processes = cpus >= 2 ? cpus : 2;
if(cluster.isMaster){
console.log("Starting server processes");
for(var i = 0; i < processes; i++){
cluster.fork();
}
cluster.on('online', worker => console.log('Worker process ' + worker.process.pid + ' is online'));
cluster.on('exit', worker => {
console.log('Worker process ' + worker.process.pid + ' has died- restarting');
cluster.fork();
});
} else {
require("./index.js");
}
@hlfshell
Copy link
Author

hlfshell commented May 3, 2017

This is the simplest clustering setup for node I've ever come across. Not the fastest (you'd have to use nginx or iptables) but pretty darned good.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment