By default, the cluster module listens for 'exit' events on workers. When a worker dies, the master process forks a new worker to keep the cluster size consistent.
The cluster module uses cluster.isMaster to check if the current process is the master. The master forks workers using cluster.fork().
const cluster = require('cluster'); if (cluster.isMaster) { for (let i = 0; i < 2; i++) { cluster.fork; } } else { console.log('Worker started'); }
The code uses cluster.fork without parentheses, so it references the function but does not execute it. Workers are never created.
const cluster = require('cluster'); if (cluster.isMaster) { console.log('Master process'); cluster.fork(); cluster.fork(); console.log('Workers count:', Object.keys(cluster.workers).length); } else { console.log('Worker process'); }
The cluster.fork() calls are asynchronous. Immediately after calling fork twice, cluster.workers is still empty, so length is 0. Worker processes print their messages separately.
Node.js cluster module uses a round-robin approach by default on most platforms, where the master distributes incoming connections evenly to workers to balance load.