0
0
Node.jsframework~5 mins

Creating worker threads in Node.js

Choose your learning style9 modes available
Introduction

Worker threads let you run code in the background without stopping your main program. This helps your app stay fast and smooth.

When you have heavy calculations that might slow down your app.
When you want to do multiple tasks at the same time.
When you want to keep your app responsive while doing background work.
When you need to run code that takes a long time without freezing the user interface.
Syntax
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('start');

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

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

Examples
This starts a worker thread running the code in worker.js.
Node.js
import { Worker } from 'worker_threads';

// Create a worker from a file
const worker = new Worker('./worker.js');
This listens for messages sent from the worker thread.
Node.js
worker.on('message', (msg) => {
  console.log('Received:', msg);
});
This sends a message to the worker thread.
Node.js
worker.postMessage('Hello Worker');
Sample Program

This example shows how to create a worker thread inside the same file. The main thread sends a message to the worker, and the worker replies back.

Node.js
import { Worker, isMainThread, parentPort } from 'worker_threads';

if (isMainThread) {
  // This is the main thread
  const worker = new Worker(new URL(import.meta.url));

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

  worker.postMessage('Hello Worker');
} else {
  // This is the worker thread
  parentPort.on('message', (msg) => {
    // Respond back with a message
    parentPort.postMessage(`Worker received: ${msg}`);
  });
}
OutputSuccess
Important Notes

Worker threads run in separate memory, so you must send messages to share data.

Use isMainThread to check if code is running in the main or worker thread.

Worker threads help keep your app fast by doing heavy work in the background.

Summary

Worker threads let you run code in parallel without blocking your main program.

You create a worker with new Worker() and communicate using messages.

This helps your app stay responsive during heavy tasks.