0
0
Node.jsframework~10 mins

Worker pool pattern in Node.js - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a new worker thread.

Node.js
const { Worker } = require('worker_threads');

const worker = new [1]('./worker.js');
Drag options to blanks, or click blank then click option'
AProcess
BThread
CTask
DWorker
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Thread' or 'Process' instead of 'Worker'.
Trying to create a worker without importing the Worker class.
2fill in blank
medium

Complete the code to send a message from the main thread to the worker.

Node.js
worker.[1]('start');
Drag options to blanks, or click blank then click option'
Asend
BpostMessage
Cemit
Dwrite
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'send' or 'emit' which are not methods of Worker.
Trying to use 'write' which is for streams.
3fill in blank
hard

Fix the error in the worker code to listen for messages.

Node.js
const { parentPort } = require('worker_threads');

parentPort.[1]('message', (msg) => {
  console.log('Received:', msg);
});
Drag options to blanks, or click blank then click option'
Aon
Bhandle
Clisten
DaddListener
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'listen' or 'handle' which are not valid methods.
Using 'addListener' which works but is less common than 'on'.
4fill in blank
hard

Fill both blanks to create a pool of 4 workers and store them in an array.

Node.js
const workers = Array.from({ length: 4 }, () => new [1]('./worker.js')); // Create 4 workers

workers.forEach(worker => worker.[2]('ready'));
Drag options to blanks, or click blank then click option'
AWorker
BpostMessage
Csend
DThread
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Thread' instead of 'Worker'.
Using 'send' instead of 'postMessage'.
5fill in blank
hard

Fill all three blanks to handle worker exit events and restart the worker.

Node.js
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');
    }
  });
});
Drag options to blanks, or click blank then click option'
Aindex
BWorker
DThread
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Thread' instead of 'Worker'.
Using different variables for the first and third blanks.