import cluster from 'cluster'; import os from 'os'; if (cluster.isPrimary) { console.log('Master process is running'); const worker = cluster.fork(); worker.on('online', () => { console.log('Worker is online'); }); } else { console.log('Worker process started'); }
The master process logs first, then forks a worker. When the worker is online, the master logs 'Worker is online'. The worker then logs 'Worker process started'. The order is master log, master event log, then worker log.
The correct method to create a worker process in Node.js cluster is cluster.fork(). Other methods do not exist and will cause errors.
import cluster from 'cluster'; if (cluster.isPrimary) { cluster.fork(); } else if (cluster.isWorker) { console.log('Worker started'); }
The property to check if the process is a worker is cluster.isWorker>. Using else if means if cluster.isPrimary is true, the worker code is skipped. Changing to separate if statements ensures the worker code runs in the worker process.
import cluster from 'cluster'; let workerCount = 0; if (cluster.isPrimary) { cluster.fork(); cluster.fork(); workerCount = Object.keys(cluster.workers).length; } else { // worker code }
After forking two workers, cluster.workers contains two keys. Counting keys gives 2.
Master and worker processes are separate. They communicate via IPC messages. Workers use process.send() to send messages to the master, which listens with worker.on('message'). They do not share memory or event loops.