Node.js › Clustering & Worker Threads
What is the difference in behavior between the 'primary' and 'worker' role in Node's cluster module regarding which code paths execute?
AdvancedAnswer
A script using the cluster module is re-executed by every forked worker as well as the primary -- code branches on cluster.isPrimary (true only in the original process), typically containing only forking/management logic, while cluster.isWorker guards the actual application logic, ensuring the primary never also runs a full server copy.
if (cluster.isPrimary) {
for (let i = 0; i < 4; i++) cluster.fork();
cluster.on('exit', () => cluster.fork());
} else {
require('./app').listen(3000);
}Real-world example A misconfigured cluster setup that started the server inside both branches got an 'address already in use' error, resolved by keeping server-starting code only in the isWorker branch.