Skip to content

Instantly share code, notes, and snippets.

@swateek
Last active October 11, 2017 06:34
Show Gist options
  • Save swateek/aecb6b9e3d7f15e4ff4c3030bb75f09b to your computer and use it in GitHub Desktop.
Save swateek/aecb6b9e3d7f15e4ff4c3030bb75f09b to your computer and use it in GitHub Desktop.
NodeJS Clusters
'use strict';
const cluster = require('cluster');
const http = require('http');
const numCores = 3;
var workerIds = [];
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
// Fork workers.
for (let i = 0; i < numCores; i++) {
cluster.fork();
}
// add workers to array
for (const id in cluster.workers) {
workerIds.push(cluster.workers[id].id)
}
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`);
});
} else {
var worker = cluster.worker.id;
if(worker == 1){ // start server
console.log("I'll start server");
http.createServer((req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);
}
if(worker == 2){ // run bull
console.log("I'll run bull");
}
if(worker == 3){ // run a third party server
console.log("Some random stuff...");
}
console.log(`Worker ${process.pid} started`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment