Skip to content

Instantly share code, notes, and snippets.

@ofanidariyan
Last active March 30, 2020 10:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ofanidariyan/8c890c945bac22a047c218e8d2317f6a to your computer and use it in GitHub Desktop.
Save ofanidariyan/8c890c945bac22a047c218e8d2317f6a to your computer and use it in GitHub Desktop.
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
const express = require('express');
var app = express();
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
// Fork workers.
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
//Check if work id is died
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`);
});
} else {
// This is Workers can share any TCP connection
// It will be initialized using express
console.log(`Worker ${process.pid} started`);
app.get('/cluster', (req, res) => {
let worker = cluster.worker.id;
res.send(`Running on worker with id ==> ${worker}`);
});
app.listen(3000, function() {
console.log('Your node is running on port 3000');
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment