Worker Thread
What are Worker Threads?
Node.js runs JavaScript in a single thread called the event loop, handling one main task at a time.
The Problem: If a task takes too long (like heavy calculations), the event loop gets blocked and the app becomes slow.
The Solution: Worker threads are helpers that run code in the background. They allow your main thread to keep working while heavy work runs separately.
How It Works
- Use the worker_threads module
- Each worker runs JavaScript in its own thread and memory space
- Main thread and worker communicate using messages
When to Use
Use worker threads for CPU-heavy tasks like:
- Image or video processing
- Complex math
- Data compression
Do not use for normal file or network tasks (Node already handles those well).
Interview Questions
Q: What is a worker thread in Node.js?
A worker thread runs JavaScript in parallel threads. It helps handle CPU-heavy tasks without blocking the main event loop.
Q: When should you use worker threads?
Use them for CPU-heavy operations that slow the main thread.
Q: Difference between worker thread and child process?
Worker threads share memory within the same process. Child processes run in separate processes and do not share memory.