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:

javascript Copy
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:

javascript Copy
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

middle

Could we run an external process with Node.js?

junior

What does Promisifying technique mean in Node.js?

middle

What is Event Loop in Node.jsWhat is Event Loop in Node.js??

Bình luận

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

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