Last active
March 30, 2020 10:11
-
-
Save ofanidariyan/8c890c945bac22a047c218e8d2317f6a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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