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

How can you have one global variable be...

Câu trả lời

To have one global variable shared between all clustered workers in Node.js, you cannot directly use a global variable because each worker in a Node.js cluster runs in its own process with its own memory space. However, there are several approaches to share state or data between these workers:

1. Using an External Store

The most common and reliable way to share data between workers is by using an external datastore like Redis. This method involves all workers reading from and writing to a shared database or in-memory data store, which acts as a central source of truth.

2. Using Node.js Cluster Messaging

You can use the messaging capabilities of the Node.js cluster module to share data between the master and worker processes. The master process can maintain the state and synchronize it across workers by sending messages to each worker whenever the shared state changes. Workers can also send messages to the master to update the state.

Here’s a basic example of how you might implement this:

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

if (cluster.isPrimary) {
    let globalCounter = 0; // Shared state

    // Fork workers.
    for (let i = 0; i < numCPUs; i++) {
        const worker = cluster.fork();

        worker.on('message', msg => {
            if (msg.type === 'increment') {
                globalCounter += 1;
                console.log(`New counter value: ${globalCounter}`);
            }
        });
    }
} else {
    process.send({ type: 'increment' });
}

In this example, workers send a message to the primary process to increment the globalCounter. The primary process handles these messages and updates the shared state.

3. Using Shared Memory Modules

There are third-party libraries that facilitate shared memory access between Node.js processes. One such library is shared-memory, which can be used to create and manage shared memory regions accessible by multiple processes. However, this approach is more complex and can introduce additional challenges related to synchronization...

senior

senior

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

junior

Why we always require modules at the top of a file? Can we require modules inside of functions?

senior

List some differences between CommonJS module loader and ECMAScript module loader

expert

How would you scale Node application?

Bình luận

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

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