Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a new worker thread.
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
Forgetting quotes around the file path.
Passing the module instead of the path string.
✗ Incorrect
You must pass the path to the worker script as a string to the Worker constructor.
2fill in blank
mediumComplete the code to send data to the worker thread.
Node.js
worker.postMessage([1]); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing a string literal instead of the data variable.
Using undefined variable names.
✗ Incorrect
You send the actual data object or value to the worker using postMessage.
3fill in blank
hardFix the error in receiving data inside the worker thread.
Node.js
const { parentPort } = require('worker_threads');
parentPort.on('message', ([1]) => {
console.log('Received:', data);
}); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different parameter name than the one logged.
Not defining the parameter at all.
✗ Incorrect
The parameter name must match the variable used inside the function to access the data.
4fill in blank
hardFill both blanks to pass initial data to the worker using workerData.
Node.js
const { Worker, [1] } = require('worker_threads');
const worker = new Worker('./worker.js', { [2]: { value: 42 } }); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'parentPort' instead of 'workerData'.
Not passing the data inside the options object.
✗ Incorrect
You import 'workerData' and pass it as an option to the Worker constructor to send initial data.
5fill in blank
hardFill all three blanks to create a worker that receives initial data and listens for messages.
Node.js
const { Worker, [1] } = require('worker_threads');
// In main thread
const worker = new Worker('./worker.js', { [2]: { name: 'Alice' } });
// In worker.js
const { parentPort, [3] } = require('worker_threads');
console.log('Name:', workerData.name);
parentPort.on('message', (msg) => {
console.log('Message:', msg);
}); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Not importing workerData in the worker file.
Confusing parentPort and workerData.
Not passing workerData in the Worker constructor options.
✗ Incorrect
You import and use 'workerData' to access initial data in the worker, and 'parentPort' to listen for messages.