|$ curl https://forge-ai.dev/api/markdown?path=docs/nodejs/worker-threads
$cat docs/worker-threads.md
updated Recently·20 min read·published
Worker Threads
Introduction
Node.js is single-threaded with an event loop. Worker threads allow you to run JavaScript in parallel, which is ideal for CPU-bound tasks like image processing, data parsing, or complex calculations.
Basic Example
worker.js
JavaScript
| 1 | const { Worker, isMainThread, parentPort, workerData } = require("worker_threads"); |
| 2 | |
| 3 | if (isMainThread) { |
| 4 | const worker = new Worker(__filename, { |
| 5 | workerData: { n: 40 }, |
| 6 | }); |
| 7 | |
| 8 | worker.on("message", (result) => console.log(result)); |
| 9 | worker.on("error", console.error); |
| 10 | worker.on("exit", (code) => { |
| 11 | if (code !== 0) console.error(`Worker stopped with code ${code}`); |
| 12 | }); |
| 13 | } else { |
| 14 | const { n } = workerData; |
| 15 | const fib = (x) => (x < 2 ? x : fib(x - 1) + fib(x - 2)); |
| 16 | parentPort.postMessage(fib(n)); |
| 17 | } |
When to Use
- Heavy computation that would block the event loop.
- Parallel data processing pipelines.
- Image, video, or audio transcoding.