Node.js Course
Node.js
/
Advanced

Worker Threads

Definition

A built-in module that enables the creation of true multi-threaded Node.js applications. Unlike clusters (which create entirely new processes), worker threads share memory and are much lighter.

Explain Like I'm New

If Clustering is cloning the entire restaurant (new building, new manager, new kitchen), Worker Threads are just hiring extra chefs for the existing kitchen. Because they are in the same kitchen, the chefs can share the same ingredients (shared memory) without having to mail them to each other.

Real World Example

An app that resizes uploaded images. Image resizing requires heavy math (CPU intensive). If the main Event Loop does the math, the server freezes for everyone else. Instead, the main loop tosses the image to a background Worker Thread. The background thread does the math, and returns the result when it's done.

Common Use Cases

  • •CPU-intensive calculations (Image processing, video encoding, cryptography)
  • •Preventing Event Loop blockage

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • Are Worker Threads used for speeding up Database queries (I/O)?

intermediate

  • How do Worker Threads communicate with the main thread?

Flash Cards

Question

Are they used for I/O?

Click to reveal answer
Answer

No. Node's built-in asynchronous I/O is already perfectly optimized for databases and network requests. Worker threads are STRICTLY for CPU-intensive tasks (heavy math) that would otherwise block the Event Loop.

Question

How do they communicate?

Click to reveal answer
Answer

Via a messaging system (Events). The main thread calls `worker.postMessage(data)`, and the worker listens via `parentPort.on('message')`.