You want to create a Node.js cluster that forks a worker for each CPU core and logs each worker's process ID. Which code snippet correctly achieves this?
hard📝 Application Q8 of 15
Node.js - Cluster Module
You want to create a Node.js cluster that forks a worker for each CPU core and logs each worker's process ID. Which code snippet correctly achieves this?
Aconst cluster = require('cluster');
const os = require('os');
if (cluster.isMaster) {
const cpus = os.cpus().length;
for (let i = 0; i < cpus; i++) {
const worker = cluster.fork();
console.log(`Worker ${worker.process.pid} started`);
}
}
Cconst cluster = require('cluster');
const os = require('os');
if (cluster.isMaster) {
cluster.fork(os.cpus().length);
}
Dconst cluster = require('cluster');
if (cluster.isMaster) {
for (let i = 0; i < 4; i++) {
cluster.fork();
}
console.log('Workers started');
}
Step-by-Step Solution
Solution:
Step 1: Use os.cpus().length to get CPU count
This is needed to fork one worker per CPU core.
Step 2: Fork workers in a loop and log each worker's PID
const cluster = require('cluster');
const os = require('os');
if (cluster.isMaster) {
const cpus = os.cpus().length;
for (let i = 0; i < cpus; i++) {
const worker = cluster.fork();
console.log(`Worker ${worker.process.pid} started`);
}
} correctly forks and logs each worker's process ID.
Step 3: Check other options for correctness
const cluster = require('cluster');
if (cluster.isWorker) {
console.log(`Worker ${process.pid} started`);
} else {
cluster.fork();
} forks only one worker, C incorrectly calls fork with argument, D forks 4 workers but does not log PIDs.
Final Answer:
Option A correctly forks per CPU and logs worker PIDs -> Option A
Quick Check:
Fork per CPU and log PID = const cluster = require('cluster');
const os = require('os');
if (cluster.isMaster) {
const cpus = os.cpus().length;
for (let i = 0; i < cpus; i++) {
const worker = cluster.fork();
console.log(`Worker ${worker.process.pid} started`);
}
} [OK]
Quick Trick:Use os.cpus().length and loop to fork workers [OK]
Common Mistakes:
Calling cluster.fork with arguments
Not logging worker PIDs
Forking fixed number without CPU count
Master "Cluster Module" in Node.js
9 interactive learning modes - each teaches the same concept differently