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 ?
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_messageIf 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?)