Skip to content

Instantly share code, notes, and snippets.

@hupptechnologies
Last active July 27, 2023 06:12
Show Gist options
  • Select an option

  • Save hupptechnologies/81b4e344daf92f1c974e86f21fa0def0 to your computer and use it in GitHub Desktop.

Select an option

Save hupptechnologies/81b4e344daf92f1c974e86f21fa0def0 to your computer and use it in GitHub Desktop.
Utilizing Node.js Cluster for Maximum CPU Efficiency
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
// Master process creates worker processes
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`Worker ${worker.process.pid} died`);
// Create a new worker if one dies
cluster.fork();
});
} else {
// Workers share the same TCP connection
http.createServer((req, res) => {
// Request handling logic
res.writeHead(200);
res.end('Hello from the server!');
}).listen(3000);
console.log(`Worker ${process.pid} started`);
}
const http = require('http');
// Normal HTTP server creation
const server = http.createServer((req, res) => {
// Request handling logic
res.writeHead(200);
res.end('Hello from the server!');
});
const port = 3000;
server.listen(port, () => {
console.log(`Server running on port ${port}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment