Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a cluster using Node.js cluster module.
Node.js
const cluster = require('cluster'); if (cluster.isMaster) { console.log('Master process is running'); cluster.fork(); } else { console.log('Worker process [1]'); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using past tense like 'started' or 'created' which is less common here.
✗ Incorrect
The worker process logs 'running' to indicate it is active.
2fill in blank
mediumComplete the code to get the number of CPU cores for clustering.
Node.js
const os = require('os'); const numCPUs = os.[1]().length; console.log(`Number of CPUs: ${numCPUs}`);
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using non-existent methods like 'cpuCount' or 'numCpus'.
✗ Incorrect
The correct method to get CPU info is os.cpus().
3fill in blank
hardFix the error in the code to properly fork workers for each CPU core.
Node.js
const cluster = require('cluster'); const os = require('os'); if (cluster.isMaster) { const cpuCount = os.cpus().length; for (let i = 0; i < [1]; i++) { cluster.fork(); } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using
os.cpus().length directly in the loop condition causes repeated calls.✗ Incorrect
The variable cpuCount holds the number of CPUs and should be used in the loop.
4fill in blank
hardFill both blanks to handle worker exit and restart a new worker.
Node.js
cluster.on('exit', (worker, code, signal) => { console.log(`Worker [1] died`); cluster.[2](); });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'restart' which is not a cluster method.
✗ Incorrect
When a worker process dies, log 'process' and fork a new worker.
5fill in blank
hardFill all three blanks to create a simple HTTP server in each worker.
Node.js
const http = require('http'); if (cluster.isWorker) { http.createServer((req, res) => { res.writeHead([1], {'Content-Type': [2]); res.end([3]); }).listen(8000); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong status codes or content types like 'application/json'.
✗ Incorrect
The server responds with status 200, content type text/plain, and a simple text message.