NodeJS集群全局variables

我试图在特定的集群中执行一个函数,但是我在主进程中分配variables时遇到了一些奇怪的问题。

const cluster = require('cluster'); let _checkId = null; // This stores the cluster id if(cluster.isMaster) { for(let i = 0; i < 4; i++) { // Assign _checkId if(_checkId === null) _checkId = (i + 1); console.log(_checkId); cluster.fork(); } } else { console.log('Cluster id: ' + cluster.worker.id); console.log('_checkId ' + _checkId); console.log(_checkId === cluster.worker.id); } 

这个输出是:

 1 1 1 Cluster id: 3 _checkId null // --> This doesn't make sense false Cluster id: 1 _checkId null false Cluster id: 2 _checkId null false 

基本上我试图实现的是,我可以有多个群集,但只有一个群集应该执行特定的function。

它正在执行你指定要做的事情:_checkId的值是null,只在你的主进程中被赋值

 const cluster = require('cluster'); let _checkId = null; // This stores the cluster id if(cluster.isMaster) { for(let i = 0; i < 4; i++) { // Assign _checkId if(_checkId === null) _checkId = (i + 1); console.log(_checkId); cluster.fork(); } } else { // _checkId remains null _checkId = 'foo'; console.log('Cluster id: ' + cluster.worker.id); console.log('_checkId ' + _checkId); console.log(_checkId === cluster.worker.id); } 

这收益率

 Cluster id: 3 _checkId foo // --> This makes sense ... Cluster id: 1 _checkId foo ... Cluster id: 2 _checkId foo ...