When working with Node.js, it's common to have a scenario where you need to declare a shared variable that can be set by the master process and accessed by worker processes. This kind of setup is often encountered in scenarios where you have a master process managing multiple worker processes, and you need a way for them to share data seamlessly. Thankfully, Node.js provides a straightforward way to achieve this through the use of shared memory and inter-process communication.
To declare a shared variable that can be initialized by the master process and accessed by worker processes, you can leverage Node.js' built-in cluster module. The cluster module allows you to create child processes (worker processes) that share server ports with the main Node.js process (master process). This makes it an ideal choice for scenarios where you need to share data between the master and worker processes efficiently.
First, you need to create a shared variable in the master process. This variable will be accessible by all worker processes. Here's an example of how you can declare a shared variable named `sharedData` in the master process:
const cluster = require('cluster');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
// Initialize the shared variable in the master process
const sharedData = 'Initial value';
// Fork worker processes
for (let i = 0; i {
if (message.type === 'getData') {
// Send the shared data to the worker process
worker.send({ type: 'sharedData', data: sharedData });
}
});
}
In this code snippet, we're initializing a shared variable named `sharedData` in the master process and forking worker processes to handle incoming requests.
Next, let's see how a worker process can access the shared variable `sharedData`:
const cluster = require('cluster');
if (cluster.isWorker) {
// Request the shared data from the master process
process.send({ type: 'getData' });
// Listen for messages from the master process
process.on('message', (message) => {
if (message.type === 'sharedData') {
// Access the shared variable sent by the master process
console.log('Shared data received:', message.data);
}
});
}
In the worker process, we're requesting the shared data from the master process and then listening for messages to access the shared variable.
By following this approach, you can easily declare a shared variable in Node.js that can be initialized by the master process and accessed by worker processes. This enables seamless communication and data sharing between different parts of your Node.js application, making it more efficient and scalable.