Complete the code to create a new worker thread.
const { Worker } = require('worker_threads');
const worker = new [1]('./worker.js');In Node.js, the Worker class from the worker_threads module is used to create a new worker thread.
Complete the code to send a message from the main thread to the worker.
worker.[1]('start');
The postMessage method sends a message to the worker thread.
Fix the error in the worker code to listen for messages.
const { parentPort } = require('worker_threads');
parentPort.[1]('message', (msg) => {
console.log('Received:', msg);
});The on method is used to listen for events like 'message' on parentPort.
Fill both blanks to create a pool of 4 workers and store them in an array.
const workers = Array.from({ length: 4 }, () => new [1]('./worker.js')); // Create 4 workers workers.forEach(worker => worker.[2]('ready'));
Use Worker to create new worker threads and postMessage to send messages to them.
Fill all three blanks to handle worker exit events and restart the worker.
workers.forEach((worker, index) => {
worker.on('exit', (code) => {
if (code !== 0) {
console.log(`Worker ${index} exited with code ${code}. Restarting...`);
workers[[1]] = new [2]('./worker.js');
workers[[3]].postMessage('start');
}
});
});Use the index to replace the exited worker, create a new Worker, and send it a 'start' message.
