Node.js

Move a small CPU task into a worker thread

Use a worker thread for CPU-bound JavaScript that would otherwise occupy the main event loop. A worker can receive input and return a result through messages.

Worked example

Node.js example · save as example.mjs and run node example.mjs

import {Worker} from "node:worker_threads";
const worker = new Worker(`
  const {parentPort, workerData} = require("node:worker_threads");
  parentPort.postMessage(workerData.reduce((sum, n) => sum + n, 0));
`, {eval: true, workerData: [1, 2, 3]});
const result = await new Promise((resolve, reject) => {
  worker.once("message", resolve);
  worker.once("error", reject);
  worker.once("exit", code => { if (code !== 0) reject(new Error(`Worker exit ${code}`)); });
});
console.log(result);

How it works

The worker runs its own JavaScript execution thread. WorkerData is cloned into that context, and the response returns through a message. The example uses fixed source text; a real project usually keeps the worker in a separate module.

Limits and mistakes

Worker startup and message transfer have overhead, so tiny operations are often slower this way. Workers do not make ordinary asynchronous file or network I/O inherently faster. Never treat eval mode as a sandbox for untrusted source.

Check the result

Expect 6 and a naturally exiting worker. Measure an actual CPU workload before adding a pool, and handle worker exit paths that do not send a result.

Sources

Reference documentation for the behavior used in this guide: