0
0
Node.jsframework~30 mins

Receiving results from workers in Node.js - Mini Project: Build & Apply

Choose your learning style9 modes available
Receiving Results from Workers in Node.js
📖 Scenario: You are building a Node.js application that uses worker threads to perform tasks in the background. You want to receive results from these workers and handle them in the main thread.
🎯 Goal: Create a simple Node.js program that starts a worker thread, sends a task to it, and receives the result back in the main thread.
📋 What You'll Learn
Create a worker thread using the worker_threads module
Send a message from the main thread to the worker
Receive a message from the worker in the main thread
Log the received result in the main thread
💡 Why This Matters
🌍 Real World
Worker threads help Node.js applications perform CPU-heavy tasks without blocking the main thread, improving responsiveness.
💼 Career
Understanding worker threads is important for backend developers building scalable and efficient Node.js applications that handle concurrent tasks.
Progress0 / 4 steps
1
Set up the worker thread file
Create a file named worker.js that imports parentPort from worker_threads and listens for messages using parentPort.on('message', ...).
Node.js
Need a hint?

Use require('worker_threads') to get parentPort. Then use parentPort.on('message', callback) to listen for messages.

2
Add a task handler in the worker
Inside the parentPort.on('message', ...) callback in worker.js, create a variable result that doubles the received value. Then send the result back to the main thread using parentPort.postMessage(result).
Node.js
Need a hint?

Multiply value by 2 and send it back with parentPort.postMessage().

3
Create the main thread file and start the worker
Create a file named main.js. Import Worker from worker_threads. Create a new Worker instance with the filename './worker.js'. Send the number 10 to the worker using worker.postMessage(10).
Node.js
Need a hint?

Use new Worker('./worker.js') to start the worker and worker.postMessage(10) to send data.

4
Receive and log the result from the worker
In main.js, add a listener for worker.on('message', ...) that receives the result from the worker and logs it using console.log with the text "Result from worker:" followed by the result.
Node.js
Need a hint?

Use worker.on('message', callback) to get the result and console.log to show it.