Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a worker thread in Node.js.
Node.js
const { Worker } = require('worker_threads');
const worker = new Worker([1]);
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting './' in the path string
Using a path without quotes
Passing a directory instead of a file
✗ Incorrect
The Worker constructor requires the path to the worker script as a string with './' prefix to indicate a relative path.
2fill in blank
mediumComplete the code to listen for the 'exit' event on the worker.
Node.js
worker.on('[1]', (code) => { console.log(`Worker exited with code ${code}`); });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'close' or 'end' which are not valid worker events
Misspelling the event name
✗ Incorrect
The 'exit' event is emitted when a worker thread stops running.
3fill in blank
hardFix the error in the code to restart the worker after it crashes.
Node.js
worker.on('exit', (code) => { if (code !== 0) { [1] = new Worker('./worker.js'); } });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a new variable name without updating references
Using the class name 'Worker' instead of the variable
✗ Incorrect
We must assign the new Worker instance back to the existing 'worker' variable to replace the crashed worker.
4fill in blank
hardFill both blanks to listen for errors and restart the worker safely.
Node.js
worker.on('[1]', (err) => { console.error('Worker error:', err); worker.[2](); worker = new Worker('./worker.js'); });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'exit' event instead of 'error' for error handling
Calling a non-existent method instead of 'terminate()'
✗ Incorrect
The 'error' event catches worker errors. Calling 'terminate()' stops the worker before restarting.
5fill in blank
hardFill all three blanks to send a message to the worker, listen for messages, and handle worker exit.
Node.js
worker.[1]({ task: 'start' }); worker.on('[2]', (msg) => { console.log('Message from worker:', msg); }); worker.on('[3]', (code) => { if (code !== 0) { console.log('Restarting worker...'); worker = new Worker('./worker.js'); } });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'send' instead of 'postMessage' to send data
Listening for wrong event names
Not handling worker exit properly
✗ Incorrect
Use 'postMessage' (A) to send messages to the worker, listen for the 'message' event (B), and handle the 'exit' event (C).