Complete the code to create a cluster that listens on port 3000.
const cluster = require('cluster'); const http = require('http'); if (cluster.isMaster) { cluster.fork(); } else { http.createServer((req, res) => { res.writeHead(200); res.end('Hello from worker [1]'); }).listen(3000); }
The process.pid gives the unique process ID of the worker, which helps identify which worker is responding.
Complete the code to create a worker thread that runs a function.
const { Worker } = require('worker_threads');
const worker = new Worker(`
const { parentPort } = require('worker_threads');
parentPort.postMessage('Hello from [1]');
`, { eval: true });The worker thread sends a message saying 'Hello from worker thread' to indicate it is running in a worker thread.
Fix the error in the cluster setup to properly fork workers equal to CPU cores.
const cluster = require('cluster'); const os = require('os'); if (cluster.isMaster) { const cpuCount = os.[1]().length; for (let i = 0; i < cpuCount; i++) { cluster.fork(); } }
The os.cpus() method returns an array of CPU cores. Its length gives the number of cores.
Fill both blanks to create a worker thread that sends a message back to the main thread.
const { Worker, isMainThread, parentPort } = require('worker_threads');
if (isMainThread) {
const worker = new Worker(__filename);
worker.on('message', (msg) => {
console.log('Received:', msg);
});
} else {
parentPort.[1]('Hello from worker');
parentPort.[2]('close', () => process.exit());
}parentPort.postMessage sends a message to the main thread, and parentPort.on listens for events like exit.
Fill all three blanks to create a cluster that restarts a worker when it exits.
const cluster = require('cluster'); const http = require('http'); if (cluster.isMaster) { cluster.fork(); cluster.on('[1]', (worker, code, signal) => { console.log(`Worker [2] died. Restarting...`); cluster.[3](); }); } else { http.createServer((req, res) => { res.end('Hello from worker'); }).listen(3000); }
The cluster listens for the 'exit' event when a worker dies, logs the worker's id, and forks a new worker to replace it.