Bird
0
0

You want to create a Node.js server that forks one worker per CPU core and restarts any worker if it crashes. Which code snippet correctly implements this behavior?

hard📝 Application Q15 of 15
Node.js - Cluster Module
You want to create a Node.js server that forks one worker per CPU core and restarts any worker if it crashes. Which code snippet correctly implements this behavior?
Aconst cluster = require('cluster'); const http = require('http'); const os = require('os'); if (cluster.isPrimary) { const numCPUs = os.cpus().length; for (let i = 0; i < numCPUs; i++) { cluster.fork(); } } else { http.createServer((req, res) => { res.writeHead(200); res.end('Hello from worker ' + process.pid); }).listen(8000); cluster.on('exit', (worker) => { console.log(`Worker ${worker.process.pid} died`); }); }
Bconst cluster = require('cluster'); const http = require('http'); const os = require('os'); if (cluster.isWorker) { const numCPUs = os.cpus().length; for (let i = 0; i < numCPUs; i++) { cluster.fork(); } } else { http.createServer((req, res) => { res.writeHead(200); res.end('Hello from worker ' + process.pid); }).listen(8000); }
Cconst cluster = require('cluster'); const http = require('http'); const os = require('os'); if (cluster.isPrimary) { const numCPUs = os.cpus().length; for (let i = 0; i < numCPUs; i++) { cluster.fork(); } cluster.on('exit', (worker) => { console.log(`Worker ${worker.process.pid} died, restarting...`); cluster.fork(); }); } else { http.createServer((req, res) => { res.writeHead(200); res.end('Hello from worker ' + process.pid); }).listen(8000); }
Dconst cluster = require('cluster'); const http = require('http'); const os = require('os'); if (cluster.isPrimary) { cluster.fork(); } else { http.createServer((req, res) => { res.writeHead(200); res.end('Hello from worker ' + process.pid); }).listen(8000); }
Step-by-Step Solution
Solution:
  1. Step 1: Fork one worker per CPU core in primary process

    In if (cluster.isPrimary), use const numCPUs = os.cpus().length; for (let i = 0; i < numCPUs; i++) cluster.fork();
  2. Step 2: Restart workers on exit event

    In primary process, cluster.on('exit', (worker) => { console.log(`Worker ${worker.process.pid} died, restarting...`); cluster.fork(); });
  3. Step 3: Worker creates HTTP server

    Workers create the HTTP server listening on port 8000, responding with their pid.
  4. Final Answer:

    forks one worker per CPU core and restarts any worker if it crashes -> Option C
  5. Quick Check:

    Primary forks os.cpus().length + cluster.on('exit', fork()) + workers create HTTP server [OK]
Quick Trick: Use cluster.on('exit') in primary to restart workers [OK]
Common Mistakes:
  • Using cluster.isWorker instead of cluster.isPrimary
  • Not restarting workers on exit
  • Forking workers inside worker process

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes