What if your app could do many heavy jobs at once without slowing down or crashing?
Why Passing data to workers in Node.js? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine you have a big task like processing thousands of images or calculations, and you try to do it all in one place, blocking everything else.
You want to split the work into smaller parts and run them at the same time, but how do you send the right information to each part?
Manually managing data between different parts of your program is tricky and slow.
You might write complicated code to share information, which can cause bugs, crashes, or slow performance.
It's hard to keep track of what data goes where and when.
Passing data to workers lets you send exactly what each worker needs to do its job.
This keeps your main program free to do other things while workers handle heavy tasks in the background.
The system handles the data safely and efficiently, so you don't have to worry about mix-ups or crashes.
const result = heavyTask(data); // blocks main thread until done
worker.postMessage(data); // sends data to worker to process asynchronously
You can run many tasks at once without freezing your app, making programs faster and smoother.
Think of a restaurant kitchen where the chef sends different orders to cooks (workers) with the exact ingredients (data) they need, so meals get ready faster without the chef doing everything alone.
Manual data sharing between tasks is slow and error-prone.
Passing data to workers lets tasks run in parallel safely.
This improves app speed and responsiveness.
Practice
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]
- Trying to set global variables inside the worker
- Sending data only after worker starts
- Using imports to pass data
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]
- Using incorrect option names like data or initialData
- Confusing message passing with initial data passing
- Missing curly braces around data
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?
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]
- Confusing workerData with message event data
- Expecting original number instead of doubled
- Not listening to 'message' event
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.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]
- Passing primitive instead of object
- Ignoring workerData structure requirements
- Not handling errors from wrong data
workerData.numbers, doubles each number, and sends back the new array. Which main thread code correctly passes data and listens for the result?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]
- Passing array directly without object wrapper
- Using wrong option name like data
- Trying to send data after worker creation
