Workers let your program do many things at once. Passing data to workers helps them know what to do.
Passing data to workers in Node.js
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Node.js
const { Worker } = require('worker_threads');
const worker = new Worker('./worker.js', { workerData: yourData });workerData is the key to send data to the worker.
The data can be any value that can be cloned, like numbers, strings, objects.
Examples
Node.js
const { Worker } = require('worker_threads');
const worker = new Worker('./worker.js', { workerData: { name: 'Alice' } });Node.js
const { Worker } = require('worker_threads');
const worker = new Worker('./worker.js', { workerData: 42 });Node.js
const { Worker } = require('worker_threads');
const worker = new Worker('./worker.js', { workerData: ['apple', 'banana'] });Sample Program
This example shows how to send data to a worker. The main file sends a task and a limit number. The worker adds numbers from 1 to the limit and sends back the result.
Node.js
/* main.js */ const { Worker } = require('worker_threads'); const worker = new Worker('./worker.js', { workerData: { task: 'count', limit: 5 } }); worker.on('message', (msg) => { console.log('Message from worker:', msg); }); worker.on('error', (err) => { console.error('Worker error:', err); }); worker.on('exit', (code) => { console.log('Worker stopped with exit code', code); }); /* worker.js */ const { parentPort, workerData } = require('worker_threads'); if (workerData.task === 'count') { let count = 0; for (let i = 1; i <= workerData.limit; i++) { count += i; } parentPort.postMessage(`Sum from 1 to ${workerData.limit} is ${count}`); } else { parentPort.postMessage('Unknown task'); }
Important Notes
Data sent with workerData is read-only inside the worker.
Use parentPort.postMessage() to send messages back to the main thread.
Workers run in separate threads, so data is cloned, not shared directly.
Summary
Workers get data through the workerData option when created.
This data tells the worker what to do or what information to use.
Workers send results back using messages with parentPort.postMessage().
Practice
1. In Node.js, how do you pass initial data to a worker thread when creating it?
easy
Solution
Step 1: Understand worker creation
When creating a worker thread, you can pass data directly using theworkerDataoption in the Worker constructor.Step 2: Recognize data passing method
This method allows the worker to access the data immediately via the importedworkerDatafrom 'worker_threads'.Final Answer:
By using theworkerDataoption in the Worker constructor -> Option AQuick 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
Solution
Step 1: Recall Worker constructor options
The correct option to pass data when creating a worker isworkerData.Step 2: Match syntax with correct option
Only new Worker('worker.js', { workerData: { value: 10 } }) usesworkerDatacorrectly; others use invalid keys.Final Answer:
new Worker('worker.js', { workerData: { value: 10 } }) -> Option AQuick 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:
And main thread code:
What will be printed to the console?
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
Solution
Step 1: Understand workerData usage
The worker receivesworkerDatawith{ num: 5 }and multipliesnumby 2.Step 2: Trace message sent back
The worker sends5 * 2 = 10back viaparentPort.postMessage, which the main thread logs.Final Answer:
10 -> Option BQuick 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?
Assuming
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
Solution
Step 1: Check workerData type
The worker expectsworkerDataas an object with avalueproperty, but a number 123 is passed.Step 2: Identify mismatch impact
This mismatch can cause errors or undefined behavior inside the worker when accessingworkerData.value.Final Answer:
workerData should be an object, not a number -> Option DQuick 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
Solution
Step 1: Verify the correct workerData structure
The worker accesses the array asworkerData.numbers, so only code passing{ workerData: { numbers: [1,2,3] } }works correctly.Step 2: Confirm result handling
The correct code includesworker.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 CQuick 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
