Bird
Raised Fist0
Node.jsframework~10 mins

Passing data to workers in Node.js - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

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
Concept Flow - Passing data to workers
Main thread starts
Create Worker
Send data to Worker
Worker receives data
Worker processes data
Worker sends result back
Main thread receives result
Main thread continues
The main thread creates a worker, sends data to it, the worker processes the data and sends back the result, which the main thread receives.
Execution Sample
Node.js
import { Worker } from 'node:worker_threads';

const worker = new Worker(`
  import { parentPort } from 'node:worker_threads';
  parentPort.on('message', data => {
    parentPort.postMessage(data * 2);
  });
`, { eval: true });

worker.on('message', result => console.log('Result:', result));
worker.postMessage(10);
This code creates a worker that doubles a number sent from the main thread and sends the result back.
Execution Table
StepActionData SentWorker StateMain Thread StateOutput
1Main thread creates workerN/AWorker initialized, waiting for messageWorker createdNo output
2Main thread sends message 1010Received 10, processingMessage 10 sentNo output
3Worker processes data10Calculates 10 * 2 = 20Waiting for worker responseNo output
4Worker sends result 2020Sent message 20Waiting for messageNo output
5Main thread receives result20Idle, waiting for next messageReceived 20Logs: Result: 20
6Execution endsN/AIdleIdleFinal output: Result: 20
💡 Worker finishes processing and main thread receives the doubled value, then execution ends.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 5Final
workerundefinedWorker instance createdWorker processing messageWorker idleWorker idle
dataSentN/A10102020
mainThreadStateStartingSent message 10Waiting for responseReceived 20Idle
Key Moments - 3 Insights
Why does the main thread not wait and block when sending data to the worker?
Because sending data to a worker is asynchronous; the main thread continues running while the worker processes the data, as shown in steps 2 and 3 of the execution_table.
How does the worker receive data from the main thread?
The worker listens for 'message' events on parentPort, which triggers when the main thread sends data, as shown in step 2 where the worker state changes to 'Received 10, processing'.
What happens if the worker sends data back before the main thread listens?
The main thread sets up a listener before sending data, ensuring it catches the worker's message, as shown in the code where worker.on('message', ...) is set before postMessage.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3. What is the worker doing?
AProcessing the received data
BWaiting for data from main thread
CSending data back to main thread
DTerminating
💡 Hint
Check the 'Worker State' column at step 3 in the execution_table.
At which step does the main thread receive the processed result?
AStep 2
BStep 3
CStep 5
DStep 6
💡 Hint
Look for 'Main Thread State' showing 'Received 20' in the execution_table.
If the main thread sends 15 instead of 10, what will the worker send back?
A10
B30
C15
D25
💡 Hint
The worker doubles the received data as shown in the code and execution_table step 3.
Concept Snapshot
Passing data to workers in Node.js:
- Create a Worker instance
- Use worker.postMessage(data) to send data
- Worker listens with parentPort.on('message')
- Worker sends back results with parentPort.postMessage(result)
- Main thread listens with worker.on('message')
- Communication is asynchronous and non-blocking
Full Transcript
In Node.js, you create a worker thread to run code separately from the main thread. The main thread sends data to the worker using postMessage. The worker listens for this data and processes it. After processing, the worker sends the result back to the main thread. The main thread listens for this result and can then continue working. This communication is asynchronous, so the main thread does not stop while the worker is busy. This allows your program to do multiple things at once without waiting.

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

  1. Step 1: Understand worker creation

    When creating a worker thread, you can pass data directly using the workerData option in the Worker constructor.
  2. Step 2: Recognize data passing method

    This method allows the worker to access the data immediately via the imported workerData from 'worker_threads'.
  3. Final Answer:

    By using the workerData option in the Worker constructor -> Option A
  4. 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

  1. Step 1: Recall Worker constructor options

    The correct option to pass data when creating a worker is workerData.
  2. Step 2: Match syntax with correct option

    Only new Worker('worker.js', { workerData: { value: 10 } }) uses workerData correctly; others use invalid keys.
  3. Final Answer:

    new Worker('worker.js', { workerData: { value: 10 } }) -> Option A
  4. 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
  • Missing curly braces around data
3. Given this worker code snippet:
const { parentPort, workerData } = require('worker_threads');
parentPort.postMessage(workerData.num * 2);

And main thread code:
const { Worker } = require('worker_threads');
const worker = new Worker('./worker.js', { workerData: { num: 5 } });
worker.on('message', (result) => console.log(result));

What will be printed to the console?
medium
A. 5
B. 10
C. undefined
D. Error

Solution

  1. Step 1: Understand workerData usage

    The worker receives workerData with { num: 5 } and multiplies num by 2.
  2. Step 2: Trace message sent back

    The worker sends 5 * 2 = 10 back via parentPort.postMessage, which the main thread logs.
  3. Final Answer:

    10 -> Option B
  4. Quick Check:

    workerData.num * 2 = 10 [OK]
Hint: Multiply workerData.num by 2 and print [OK]
Common Mistakes:
  • Confusing workerData with message event data
  • Expecting original number instead of doubled
  • Not listening to 'message' event
4. What is wrong with this code snippet for passing data to a worker?
const { Worker } = require('worker_threads');
const worker = new Worker('./worker.js', { workerData: 123 });
worker.on('message', (msg) => console.log(msg));

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

  1. Step 1: Check workerData type

    The worker expects workerData as an object with a value property, but a number 123 is passed.
  2. Step 2: Identify mismatch impact

    This mismatch can cause errors or undefined behavior inside the worker when accessing workerData.value.
  3. Final Answer:

    workerData should be an object, not a number -> Option D
  4. 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

  1. 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.
  2. 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.
  3. Final Answer:

    const worker = new Worker('./worker.js', { workerData: { numbers: [1,2,3] } }); worker.on('message', (result) => console.log(result)); -> Option C
  4. 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]
Common Mistakes:
  • Passing array directly without object wrapper
  • Using wrong option name like data
  • Trying to send data after worker creation