Bird
0
0

What will be the output if you run this code on a machine with 2 CPU cores?

medium📝 component behavior Q4 of 15
Node.js - Cluster Module
What will be the output if you run this code on a machine with 2 CPU cores?
const cluster = require('cluster');
const os = require('os');
if (cluster.isPrimary) {
  console.log('Primary process');
  for (let i = 0; i < os.cpus().length; i++) {
    cluster.fork();
  }
} else {
  console.log('Worker process');
}
APrimary process\nWorker process\nWorker process
BWorker process\nWorker process
CPrimary process\nPrimary process
DWorker process
Step-by-Step Solution
Solution:
  1. Step 1: Understand cluster.isPrimary and forking

    The primary process logs 'Primary process' once, then forks two workers (because 2 CPU cores).
  2. Step 2: Worker processes log separately

    Each worker logs 'Worker process', so two such lines appear.
  3. Final Answer:

    Primary process\nWorker process\nWorker process -> Option A
  4. Quick Check:

    Output with 2 cores = C [OK]
Quick Trick: Primary logs once; each worker logs once per core [OK]
Common Mistakes:
  • Expecting only one worker log
  • Confusing primary and worker logs
  • Thinking workers run in primary process

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes