worker_threads
- Node.js course
- Advanced
- Lesson 7/83
- 5 min
Learn CPU-heavy tasks with worker_threads.
What is worker_threads?
The Node.js event loop is single-threaded; heavy CPU work can block the whole process. The worker_threads module lets you create true parallel threads. Unlike cluster, workers are not separate processes but parallel threads inside the same process, and they can share memory.
The module is built in: you import it with require("worker_threads"). It is ideal for CPU-heavy work (image processing, cryptography, big calculations). For I/O work the event loop is already enough.
isMainThread and parentPort
The worker_threads module exposes two key properties. isMainThread returns true in the main thread and false in a worker. parentPort gives the worker a port to message the parent; it is null in the main thread.
A typical pattern: the main thread starts a worker with new Worker(...); the worker sends results back with parentPort.postMessage(...). This mirrors cluster's IPC model but runs inside a single process.
Practice Log the isMainThread value
Import isMainThread from worker_threads. Log its value with console.log.
Starter code
// import the module, get the main flag
// log its valueSample solution
const { isMainThread } = require("worker_threads");
console.log(isMainThread);Expected output
true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is worker_threads used for?
- Speeding up network requests
- Shortening file writes
- Running CPU-heavy work in parallel Correct answer
- Rendering an HTML page
Explanation: worker_threads is used to parallelize CPU-heavy work.
2 Complete the module name
const { Worker } = require("____")
const { Worker } = require("worker_threads")
Explanation: The worker_threads module loads as 'worker_threads'.
3 Match each piece to its role
| Term | Meaning |
|---|---|
worker_threads |
Parallel threads |
isMainThread |
Main thread? |
parentPort |
Parent link |
Worker |
Worker class |