Node.js Worker Threads Module

Here’s a detailed guide on the Node.js Worker Threads Module, including its purpose, usage, examples, and best practices.


🧵 Node.js Worker Threads Module

The worker_threads module allows Node.js to run JavaScript in parallel threads. Unlike the Cluster Module which creates separate processes, Worker Threads run in the same memory space, making them suitable for CPU-intensive tasks without blocking the main event loop.


1️⃣ Importing the Module



 


2️⃣ Basic Usage


 

✅ Output:

Main thread: 12345
Worker thread: 12346
Result from worker: 20

3️⃣ Creating a Worker from a Separate File

worker.js:


 

main.js:


 


4️⃣ Passing Messages Between Threads

  • Main thread → Worker:



 

  • Worker → Main thread:



 

  • Two-way communication is fully supported via parentPort.


5️⃣ Using Shared Memory with SharedArrayBuffer

Workers can share memory without copying data:


 

In worker.js:



 

  • Shared memory is efficient for high-performance tasks.


6️⃣ Worker Pool for Parallel Tasks

Instead of creating a new worker for each task, use a pool:


 

// Dispatch tasks to workers and handle messages

  • Efficient for CPU-intensive operations like image processing or math computations.


7️⃣ Advantages of Worker Threads

  1. Runs JS in parallel threads without blocking event loop

  2. Shares memory efficiently with SharedArrayBuffer

  3. Ideal for CPU-bound tasks

  4. Full support for message passing between threads


8️⃣ Differences Between Cluster & Worker Threads

Feature Cluster Worker Threads
Memory Separate processes Shared memory
IPC Messages via cluster Messages via parentPort
Use Case HTTP servers scaling CPU-heavy tasks parallelism
Resource High overhead Low overhead
Restart Master handles Worker can exit, manual restart

9️⃣ Best Practices

  1. Use worker threads for CPU-intensive tasks, not I/O tasks

  2. Reuse threads using worker pools to avoid overhead

  3. Handle errors and exit events to prevent crashes

  4. Avoid blocking the event loop in main thread

  5. Consider combining Cluster + Worker Threads for heavy production apps


10️⃣ Example: Parallel Fibonacci Computation

worker.js:


 

main.js:


 


11️⃣ Summary

  • worker_threads provides parallel execution in Node.js

  • Use Worker, parentPort, and workerData for communication

  • Ideal for CPU-bound tasks, heavy computation, and shared memory operations

  • Combine with Cluster for multi-core HTTP servers handling CPU-intensive work

You may also like...