0
0
Node.jsframework~30 mins

Passing data to workers in Node.js - Mini Project: Build & Apply

Choose your learning style9 modes available
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
Need a 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
Need a 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
Need a 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
Need a hint?

Use worker.on('message', (result) => { ... }) to get the result from the worker and store it in finalResult.