Skip to content

Instantly share code, notes, and snippets.

@himanshupal
Created September 8, 2023 15:58
Show Gist options
  • Save himanshupal/324ae6b3ce054dcd66ab8f758305abe8 to your computer and use it in GitHub Desktop.
Save himanshupal/324ae6b3ce054dcd66ab8f758305abe8 to your computer and use it in GitHub Desktop.
Simple express server that forks multiple processes so each process may answer individual requests in case of some blocking task; pm2 provides something similar that doesn't require to write this code at all.
const express = require("express");
const cluster = require("cluster");
const totalCPUs = require("os").cpus().length;
const port = 3000;
if (cluster.isMaster) {
console.log(`Number of CPUs is ${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("Hello World!");
});
app.get("/api/:n", function (req, res) {
let n = parseInt(req.params.n);
let count = 0;
if (n > 5000000000) n = 5000000000;
for (let i = 0; i <= n; i++) {
count += i;
}
res.send(`Final count is ${count}`);
});
app.listen(port, () => {
console.log(`App listening on port ${port}`);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment