Optimize Performance with cluster Module

by

in

Tip:

Use the cluster module to take advantage of multi-core systems by creating child processes that share the same server port.

Example:

javascriptCopy codeconst cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
    console.log(`Master ${process.pid} is running`);

    for (let i = 0; i < numCPUs; i++) {
        cluster.fork();
    }

    cluster.on('exit', (worker, code, signal) => {
        console.log(`Worker ${worker.process.pid} died`);
    });
} else {
    http.createServer((req, res) => {
        res.writeHead(200);
        res.end('Hello, World!\n');
    }).listen(8000);
    console.log(`Worker ${process.pid} started`);
}

Reason: Clustering enables better CPU utilization and can handle more concurrent connections by distributing the load.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *