Worker Threads
๐ Covered in this chapter:
CPU-Intensive Tasks ยท Creating a Worker ยท Message Passing ยท Worker Pools
Offload CPU-intensive JavaScript work to separate threads using node:worker_threads, without blocking the main event loop.
1Worker Threads โ What You'll Learn
Offload CPU-intensive JavaScript work to separate threads using node:worker_threads, without blocking the main event loop.
Here's everything this chapter covers, in the order you'll learn it:
- What worker threads are
- Identifying CPU-intensive tasks
- Creating a worker
- Sending messages to a worker
- Receiving messages from a worker
- Handling worker errors
- Terminating a worker
- Worker pools for reusing threads
- Worker threads vs async I/O โ when to use each
- Running parallel calculations
2Working Example
๐ป Example: Worker Threads
JavaScript
โถ Run in Compiler
import { Worker } from "node:worker_threads";
const worker = new Worker("./heavy-task.js");
worker.on("message", (result) => {
console.log("Result from worker:", result);
});
worker.postMessage({ number: 42 });
3Best Practices & Common Pitfalls
๐ก Key things to remember:
- Worker threads are for CPU-bound work (heavy calculations); they are NOT needed for I/O-bound work like database or file access, which Node already handles asynchronously and efficiently.
โ Frequently Asked Questions (FAQ)
Q What's the most important thing to understand about worker threads?
Focus on: CPU-Intensive Tasks ยท Creating a Worker ยท Message Passing ยท Worker Pools. These are the core building blocks this chapter's examples are built around, and they show up repeatedly in later chapters of this course.
Q Do I need external npm packages for worker threads?
Only where explicitly shown in the code examples above (like Express, Zod, or Socket.IO) โ otherwise, this chapter relies entirely on Node.js's own built-in capabilities.