worker_threads

Worker Threads

While fork creates entire new processes (with their own memory), Worker Threads allow you to run JavaScript in parallel within the same process. This is the official way to handle CPU-intensive tasks in Node.js without blocking the main Event Loop.

1. Why Worker Threads?


Node.js is famous for being "single-threaded," which is great for I/O (like database queries or network requests). however, if you perform a heavy calculation (like image processing or complex math), the main thread stops everything else—including responding to other users.

Worker Threads solve this by:

  • Running heavy logic on a separate thread.

  • Sharing memory with the main thread (using SharedArrayBuffer), which is much faster than the IPC used in fork.


2. Key Components of worker_threads


  • Worker: The class used to create a new thread.

  • isMainThread: A boolean that tells you if the code is running in the main thread or a worker.

  • parentPort: The way a worker sends messages back to the main thread.

  • workerData: Data passed from the main thread to the worker when it is first created.


3. Basic Example


You can write the main logic and the worker logic in the same file using isMainThread.


const { Worker, isMainThread, parentPort, workerData } = require('worker_threads');

if (isMainThread) {
  // --- MAIN THREAD ---
  console.log('Main Thread: Starting a heavy task...');
  
  const worker = new Worker(__filename, {
    workerData: { num: 40 } // Passing data to worker
  });

  worker.on('message', (result) => {
    console.log(`Main Thread: Task complete! Result: ${result}`);
  });

  worker.on('error', (err) => console.error(err));
} else {
  // --- WORKER THREAD ---
  const { num } = workerData;
  
  // Simulate a CPU-heavy task (Fibonacci)
  function fib(n) {
    if (n < 2) return n;
    return fib(n - 1) + fib(n - 2);
  }

  const result = fib(num);
  parentPort.postMessage(result); // Send result back
}


Featurechild_process.fork()worker_threads
InstanceNew Process (New PID)New Thread (Same PID)
MemoryIsolated (Expensive to copy)Shared (Very fast)
OverheadHigh (Starts a new V8 engine)Low (Lightweight)
CommunicationJSON via IPCMessages or SharedArrayBuffer
Best ForScaling across CPU coresOffloading specific CPU tasks



5. When to use this for your projects?


  1. PDF Generation: Generating study certificates or resumes from user data.

  2. Data Analysis: Running algorithms to match students with the best job listings.

  3. Image Optimization: Resizing user profile pictures or study material thumbnails on the fly.


6. Best Practice: Worker Pools

Creating and destroying a thread takes time and resources. If you have many small tasks, don't create a new Worker for every single one. Instead, use a Worker Pool (like the piscina library) to keep a set of threads alive and "feed" them tasks as they become available.