Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Passing data to workers in Node.js
📖 Scenario: You are building a Node.js application that needs to perform a heavy calculation without blocking the main program. To do this, you will use a worker thread and pass data to it.
🎯 Goal: Create a worker thread in Node.js and pass a number to it. The worker will calculate the square of the number and send the result back.
📋 What You'll Learn
Create a worker thread using the worker_threads module
Pass a number to the worker using workerData
In the worker, calculate the square of the number
Send the result back to the main thread using parentPort.postMessage
Receive the result in the main thread and handle it
💡 Why This Matters
🌍 Real World
Using worker threads helps Node.js applications perform heavy tasks without freezing the user interface or main process.
💼 Career
Understanding how to pass data to workers and handle their responses is important for building efficient, scalable Node.js applications.
Progress0 / 4 steps
1
Set up the main thread with worker import and data
Create a constant called Worker by requiring 'worker_threads' module. Then create a constant called numberToSquare and set it to 7.
Node.js
Hint
Use require('worker_threads') to get the Worker class. Then create a variable numberToSquare with value 7.
2
Create a worker and pass data using workerData
Create a new Worker instance called worker using new Worker. Pass the filename __filename and an options object with workerData set to numberToSquare.
Node.js
Hint
Use new Worker(__filename, { workerData: numberToSquare }) to create the worker and pass the data.
3
Add worker code to calculate square and send result
Check if !isMainThread. If true, import workerData and parentPort from worker_threads. Calculate the square of workerData and send it back using parentPort.postMessage.
Node.js
Hint
Use if (isMainThread) to separate main and worker code. In the worker, calculate square and send it with parentPort.postMessage.
4
Receive the result from worker in main thread
Inside the if (isMainThread) block, add an event listener on worker for 'message'. The listener function should receive result and assign it to a constant called finalResult.
Node.js
Hint
Use worker.on('message', (result) => { ... }) to get the result from the worker and store it in finalResult.
Practice
(1/5)
1. In Node.js, how do you pass initial data to a worker thread when creating it?
easy
A. By using the workerData option in the Worker constructor
B. By sending a message after the worker starts
C. By setting a global variable inside the worker file
D. By importing a module inside the worker
Solution
Step 1: Understand worker creation
When creating a worker thread, you can pass data directly using the workerData option in the Worker constructor.
Step 2: Recognize data passing method
This method allows the worker to access the data immediately via the imported workerData from 'worker_threads'.
Final Answer:
By using the workerData option in the Worker constructor -> Option A
Quick Check:
Initial data to worker = workerData option [OK]
Hint: Pass data at creation with workerData option [OK]
Common Mistakes:
Trying to set global variables inside the worker
Sending data only after worker starts
Using imports to pass data
2. Which of the following is the correct syntax to create a worker and pass data to it?
easy
A. new Worker('worker.js', { workerData: { value: 10 } })
B. new Worker('worker.js', { message: { value: 10 } })
C. new Worker('worker.js', { initialData: { value: 10 } })
D. new Worker('worker.js', { data: { value: 10 } })
Solution
Step 1: Recall Worker constructor options
The correct option to pass data when creating a worker is workerData.
Step 2: Match syntax with correct option
Only new Worker('worker.js', { workerData: { value: 10 } }) uses workerData correctly; others use invalid keys.
Final Answer:
new Worker('worker.js', { workerData: { value: 10 } }) -> Option A
Quick Check:
Correct option key = workerData [OK]
Hint: Use workerData option exactly in Worker constructor [OK]
Common Mistakes:
Using incorrect option names like data or initialData
Confusing message passing with initial data passing
Assuming worker.js expects workerData to be an object with a value property.
medium
A. Worker file path is incorrect
B. Missing event listener for 'error'
C. postMessage is missing in main thread
D. workerData should be an object, not a number
Solution
Step 1: Check workerData type
The worker expects workerData as an object with a value property, but a number 123 is passed.
Step 2: Identify mismatch impact
This mismatch can cause errors or undefined behavior inside the worker when accessing workerData.value.
Final Answer:
workerData should be an object, not a number -> Option D
Quick Check:
workerData type must match expected structure [OK]
Hint: Pass workerData as expected object type [OK]
Common Mistakes:
Passing primitive instead of object
Ignoring workerData structure requirements
Not handling errors from wrong data
5. You want to create a worker that receives an array of numbers as workerData.numbers, doubles each number, and sends back the new array. Which main thread code correctly passes data and listens for the result?
hard
A. const worker = new Worker('./worker.js', { workerData: [1,2,3] });
worker.on('message', (result) => console.log(result));
B. const worker = new Worker('./worker.js', { data: [1,2,3] });
worker.on('message', (result) => console.log(result));
C. const worker = new Worker('./worker.js', { workerData: { numbers: [1,2,3] } });
worker.on('message', (result) => console.log(result));
D. const worker = new Worker('./worker.js');
worker.postMessage([1,2,3]);
worker.on('message', (result) => console.log(result));
Solution
Step 1: Verify the correct workerData structure
The worker accesses the array as workerData.numbers, so only code passing { workerData: { numbers: [1,2,3] } } works correctly.
Step 2: Confirm result handling
The correct code includes worker.on('message', (result) => console.log(result)) to log the doubled array sent back by the worker.
Final Answer:
const worker = new Worker('./worker.js', { workerData: { numbers: [1,2,3] } });
worker.on('message', (result) => console.log(result)); -> Option C
Quick Check:
Pass array inside object via workerData and listen for message [OK]
Hint: Wrap array in object for workerData and listen to message [OK]