what is the difference between defining variables inside or outside the master code in a Nodejs Cluster?

31 views Asked by At

I am using a cluster and trying to figure out what is the best way to define variables.

 1 - var config  
 if (cluster.isMaster) {
    2 - var config
    // master code 
    for (var i = 0; i < numCPUs; i++) {
          cluster.fork() 
    }   
 }else{
    // worker code
    3 - var config  
 }

is it the same to declare variable anywhere and each worker will have its own independent copy of the variable ?

1

There are 1 answers

0
Vic On BEST ANSWER

Cluster intends for the parent process to fork itself into child processes. Processes do not share variables (even globals), so you'll have to share the state through another way.

You can have the child processes communicate with the parent process through .send() and .on("message"). https://nodejs.org/api/cluster.html#cluster_event_message

If you want a more streamlined approach, have the processes share a database through something like memshared, but you would have to deal with its asynchronous nature. (Maybe convert it into a promise then use async/await?)