Skip to content

Instantly share code, notes, and snippets.

@prashant1k99
Forked from learncodeacademy/cluster.md
Created January 20, 2019 05:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prashant1k99/e9d25b4c2fb89838a7f1dbaa8614b36d to your computer and use it in GitHub Desktop.
Save prashant1k99/e9d25b4c2fb89838a7f1dbaa8614b36d to your computer and use it in GitHub Desktop.
Node Cluster - Enhance your node app by using all the cores of your processor.

Here's all you have to do to add clustering to your node.js application.

  • save this code as cluster.js, and run cluster.js instead of server.js (or /bin/www, or whatever it's called for your project)
  • the only line you'll need to change is the last line - it needs to point to the location of your server.js file
var cluster = require('cluster');

if (cluster.isMaster) {
  // Count the machine's CPUs
  var cpuCount = require('os').cpus().length;

  // Create a worker for each CPU
  for (var i = 0; i < cpuCount; i += 1) {
    cluster.fork();
  }

  // Listen for dying workers
  cluster.on('exit', function () {
    cluster.fork();
  });
} else {
  require('./server');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment