Câu hỏi phỏng vấn Nodejs
Câu hỏi

How would you implement process communica...

Câu trả lời

To implement process communication when using the cluster module in Node.js, you can utilize the built-in Inter-Process Communication (IPC) capabilities that the cluster module provides. Here's a detailed explanation of how to achieve this:

Overview of Cluster Module and IPC

The Node.js cluster module allows you to create child processes (workers), which can run simultaneously and communicate with the master process. This is particularly useful for taking advantage of multi-core systems to improve the performance of Node.js applications[1][2][3][4][5][6][11].

Setting Up the Cluster Module

First, you need to include the cluster module in your Node.js application and check if the current process is the master process. If it is, you can fork worker processes; otherwise, you define the worker behavior:

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.
    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, it is an HTTP server
    http.createServer((req, res) => {
        res.writeHead(200);
        res.end('hello world\n');
    }).listen(8000);

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

Implementing IPC in Cluster

IPC in the cluster module is automatically set up when you fork a new worker. Workers can communicate with the master process using process.send() and the master can listen to these messages with the worker.on('message') event:

if (cluster.isMaster) {
    for (const id in cluster.workers) {
        cluster.workers[id].on('message', (msg) => {
            console.log(`Message from worker ${id}: ${msg}`);
        });
    }
} else {
    process.send('Hello Master!');
}

Customizing IPC Messages

You can customize the messages sent between the master and workers to handle specific tas...

expert

expert

Gợi ý câu hỏi phỏng vấn

senior

How to gracefully shutdown Node.js server?

junior

What is Callback?

middle

Is there any difference between res.send and return res.send in Express.js?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào