I want to use cluster module to run express server side by side using worker process. Here is my complete script.
const express = require('express');
const cluster = require('cluster');
const os = require('os');
const totalCPUs = os.cpus().length;
const PORT = 3000;
if (cluster.isMaster) {
console.log(`Number of logical cpus is available: ${totalCPUs}`);
console.log(`Master ${process.pid} is running`);
// Fork workers
for (let i = 0; i < totalCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`);
console.log("Let's fork another worker!");
cluster.fork();
});
} else {
const app = express();
console.log(`Worker ${process.pid} started`);
app.get('/', (req, res) => {
res.send(`Performance example: ${process.pid} `);
});
function spin(duration) {
const startTime = Date.now();
while (Date.now() - startTime < duration) {
// block the event loop
}
}
app.get('/delay', (req, res) => {
// after some delay
spin(9000);
res.send(`Ding ding ding! ${process.pid}`);
});
app.listen(PORT, () => {
console.log(`Worker process ${process.pid} Listening on ${PORT}`);
});
}
Whenever I open multiple tab in browser and hit same http://localhost:3000/delay
api then all request run in series by only last created child process. How would I use remain all child process ?