0
0
Node.jsframework~5 mins

Why worker threads matter in Node.js

Choose your learning style9 modes available
Introduction

Worker threads let Node.js do many things at once without slowing down. They help run heavy tasks separately so your app stays fast and smooth.

When you have a big calculation that takes time and you don't want to freeze the app.
When you want to handle multiple tasks at the same time without waiting for one to finish.
When you need to keep the app responsive while doing background work.
When you want to use multiple CPU cores to speed up processing.
When you want to avoid blocking the main thread with heavy tasks.
Syntax
Node.js
import { Worker } from 'worker_threads';

const worker = new Worker('./worker.js');

worker.on('message', (result) => {
  console.log('Result from worker:', result);
});

worker.postMessage('start');

The Worker class creates a new thread running a separate file.

You communicate with the worker using postMessage and listen for messages with on('message').

Examples
This example sends a message to the worker and logs the reply.
Node.js
import { Worker } from 'worker_threads';

const worker = new Worker('./worker.js');

worker.on('message', (msg) => {
  console.log('Message from worker:', msg);
});

worker.postMessage('Hello Worker');
This example creates a worker from a string and converts messages to uppercase.
Node.js
import { Worker } from 'worker_threads';

const worker = new Worker(`
  const { parentPort } = require('worker_threads');
  parentPort.on('message', (msg) => {
    parentPort.postMessage(msg.toUpperCase());
  });
`, { eval: true });

worker.on('message', (msg) => {
  console.log('Uppercase:', msg);
});

worker.postMessage('hello');
Sample Program

This program calculates the 10th Fibonacci number in a worker thread. It keeps the main app free to do other things while the calculation runs.

Node.js
import { Worker } from 'worker_threads';

function runWorker() {
  return new Promise((resolve, reject) => {
    const worker = new Worker(`
      const { parentPort } = require('worker_threads');
      function fibonacci(n) {
        if (n <= 1) return n;
        return fibonacci(n - 1) + fibonacci(n - 2);
      }
      parentPort.on('message', (num) => {
        const result = fibonacci(num);
        parentPort.postMessage(result);
      });
    `, { eval: true });

    worker.on('message', resolve);
    worker.on('error', reject);
    worker.postMessage(10);
  });
}

(async () => {
  const result = await runWorker();
  console.log('Fibonacci of 10 is', result);
})();
OutputSuccess
Important Notes

Worker threads run in separate memory, so you must send data back and forth using messages.

Use worker threads for CPU-heavy tasks, not for simple I/O operations.

Remember to handle errors from workers to avoid crashes.

Summary

Worker threads help Node.js run heavy tasks without freezing the app.

They let you use multiple CPU cores by running code in parallel.

You communicate with workers using messages to keep your app responsive.