0
0
Node.jsframework~10 mins

Passing data to workers 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 Worker([1]);
Drag options to blanks, or click blank then click option'
A'./worker.js'
Bworker.js
Cnew Worker()
Drequire('worker_threads')
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting quotes around the file path.
Passing the module instead of the path string.
2fill in blank
medium

Complete the code to send data to the worker thread.

Node.js
worker.postMessage([1]);
Drag options to blanks, or click blank then click option'
Adata
B'data'
CworkerData
Dmessage
Attempts:
3 left
💡 Hint
Common Mistakes
Passing a string literal instead of the data variable.
Using undefined variable names.
3fill in blank
hard

Fix 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'
Amsg
Bmessage
Cevent
Ddata
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different parameter name than the one logged.
Not defining the parameter at all.
4fill in blank
hard

Fill 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'
AworkerData
BparentPort
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'parentPort' instead of 'workerData'.
Not passing the data inside the options object.
5fill in blank
hard

Fill 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'
AworkerData
DparentPort
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.