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:
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:
-
Efficient for CPU-intensive operations like image processing or math computations.
7️⃣ Advantages of Worker Threads
-
Runs JS in parallel threads without blocking event loop
-
Shares memory efficiently with
SharedArrayBuffer -
Ideal for CPU-bound tasks
-
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
-
Use worker threads for CPU-intensive tasks, not I/O tasks
-
Reuse threads using worker pools to avoid overhead
-
Handle errors and exit events to prevent crashes
-
Avoid blocking the event loop in main thread
-
Consider combining Cluster + Worker Threads for heavy production apps
10️⃣ Example: Parallel Fibonacci Computation
worker.js:
main.js:
11️⃣ Summary
-
worker_threadsprovides parallel execution in Node.js -
Use
Worker,parentPort, andworkerDatafor communication -
Ideal for CPU-bound tasks, heavy computation, and shared memory operations
-
Combine with Cluster for multi-core HTTP servers handling CPU-intensive work
