0
0
Node.jsframework~10 mins

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

Choose your learning style9 modes available
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.