NA +91-8727899942 thecoderjob@gmail.com

CHAPTER - 26

How to add clustering in Node Js

Clustering in Node.js refers to the technique of spawning multiple processes (workers) to take advantage of multi-core systems.

This allows Node.js applications to handle more requests by distributing the workload across multiple CPU cores.

The built-in cluster module in Node.js provides an easy way to implement clustering.

Here's is the Code !!

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

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

    // Fork workers equal to the number of CPU cores
    for (let i = 0; i < numCPUs; i++) {
        cluster.fork();
    }

    cluster.on('exit', (worker, code, signal) => {
        console.log(`Worker ${worker.process.pid} died`);
    });
} else {
    // Workers can share any TCP connection
    // In this case, an HTTP server
    http.createServer((req, res) => {
        res.writeHead(200);
        res.end('Hello from worker
');
    }).listen(8000);

    console.log(`Worker ${process.pid} started`);
}

Chapter 25

Concept of streams and buffers in node js

Previous chapter

Get In Touch

NA

thecoderjob@gmail.com

+91-8727899942

Popular Links

© www.thecoderjob.com. All Rights Reserved.               Designed by HTML Codex