Bird
0
0

What output will the following Node.js cluster code produce?

medium📝 component behavior Q4 of 15
Node.js - Worker Threads
What output will the following Node.js cluster code produce?
const cluster = require('cluster');
if (cluster.isPrimary) {
  cluster.fork();
  cluster.fork();
} else {
  console.log(`Worker ${cluster.worker.id} is running`);
}
AError because cluster.isPrimary is undefined
BOne line: 'Worker 1 is running'
CNo output because cluster.fork() is called in the worker
DTwo lines: 'Worker 1 is running' and 'Worker 2 is running'
Step-by-Step Solution
Solution:
  1. Step 1: Identify primary process

    cluster.isPrimary is true in the main process, so it forks two workers.
  2. Step 2: Worker processes run else block

    Each worker logs its id with console.log.
  3. Final Answer:

    Two lines printed: 'Worker 1 is running' and 'Worker 2 is running' (Two lines: 'Worker 1 is running' and 'Worker 2 is running').
  4. Quick Check:

    Primary forks workers; workers execute else block. [OK]
Quick Trick: Primary forks workers; workers run else block. [OK]
Common Mistakes:
  • Confusing cluster.isPrimary with cluster.isWorker
  • Expecting output from primary process
  • Calling cluster.fork() inside worker process

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes