0
0
Node.jsframework~30 mins

Why worker threads matter in Node.js - See It in Action

Choose your learning style9 modes available
Why Worker Threads Matter in Node.js
📖 Scenario: You are building a Node.js application that needs to perform a heavy calculation without freezing the main program. Normally, Node.js runs code on a single thread, so heavy tasks can make the app slow or unresponsive.Worker threads let you run heavy tasks in the background, like having a helper do the hard work while you keep talking to your users.
🎯 Goal: Build a simple Node.js program that uses a Worker thread to calculate the sum of numbers from 1 to 1,000,000 without blocking the main thread.
📋 What You'll Learn
Create a variable with the number 1,000,000
Create a worker thread using the worker_threads module
Send the number to the worker thread
Receive the result from the worker thread and log it
💡 Why This Matters
🌍 Real World
Worker threads help keep Node.js applications responsive by running heavy tasks in the background, like image processing or data crunching, while the main thread handles user requests smoothly.
💼 Career
Understanding worker threads is important for backend developers working with Node.js to build scalable and efficient applications that handle heavy computations without slowing down.
Progress0 / 4 steps
1
Set up the number to sum
Create a variable called maxNumber and set it to 1000000.
Node.js
Need a hint?

Use const maxNumber = 1000000; to create the variable.

2
Import Worker and create a worker thread
Import Worker and isMainThread from the worker_threads module. Then create a new Worker instance that runs the current file if isMainThread is true.
Node.js
Need a hint?

Use const { Worker, isMainThread, parentPort } = require('worker_threads'); and new Worker(__filename);

3
Send data to worker and calculate sum
Inside the if (isMainThread) block, send maxNumber to the worker using worker.postMessage(maxNumber). Outside that block, add code for the worker thread to listen for messages with parentPort.on('message') and calculate the sum of numbers from 1 to the received number.
Node.js
Need a hint?

Use worker.postMessage(maxNumber); to send data and parentPort.on('message', (max) => { ... }); to receive it in the worker.

4
Receive result from worker and log it
In the if (isMainThread) block, add a listener for worker.on('message') to receive the sum result from the worker and log it using console.log.
Node.js
Need a hint?

Use worker.on('message', (result) => { console.log(...); }); to get the result and show it.