Prevent multiple console logging output while clus

2019-08-18 09:11发布

I'm using the cluster module for nodejs.

Here is how I have it set up:

var cluster = require('cluster');
if (cluster.isMaster) {
  var numCPUs = require('os').cpus().length;
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }
}else{
     console.log("Turkey Test");
}

Now, I am forking 6 threads (6 cores) on my PC. So, when debugging my app and reading data from the console, this will appear:

Is there anyway to make console.log output only once regardless of how many clusters are running?

1条回答
甜甜的少女心
2楼-- · 2019-08-18 09:30

You could use the fact that you can communicate with the workers, and send a message that tells each worker if it should log or not. You'd send it so that only one worker (The first one for example) should log:

var cluster = require('cluster');
if (cluster.isMaster) {
  var numCPUs = require('os').cpus().length;
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork().send({doLog: i == 0});
  }
}else{
  process.on('message', function(msg) {
    if(msg.doLog) {
      console.log('Turkey Test');
    }
  });
}
查看更多
登录 后发表回答