Worker threads in Node.js are a way to run JavaScript code in parallel on multiple threads, allowing CPU-intensive tasks to be executed without blocking the main event loop. This is particularly important in Node.js because it is single-threaded by default, and long-running computations can block the entire server if not offloaded properly.
What Are Worker Threads?
-
Introduced in Node.js v10.5.0 (stable in v12+).
-
Part of the
worker_threads
module. -
Each worker thread runs in its own isolated V8 instance.
-
Communication is done via messages or shared memory.
When to Use Worker Threads:
Use them when:
-
You have CPU-intensive tasks: like data processing, image/video manipulation, cryptography, or large JSON parsing.
-
You want to avoid blocking the event loop: which can degrade performance for other incoming requests.
-
You need true parallelism: not just asynchronous I/O.
-
You want better performance over spawning separate processes: since threads are more lightweight than child processes.
Example Use Case:
And in worker.js
: