bhylu.com

Advertisements

Node.js Worker Threads

Worker threads execute JavaScript in separate isolates within one process. They are useful for selected CPU work, not a reason to wrap every asynchronous I/O call in another thread.

How it works

The complete file has a main-thread branch and a worker branch. The parent supplies a small cloneable input, observes the result and awaits the worker’s exit. A real application should use a bounded pool, handle failures and apply cancellation policy rather than starting unlimited workers per request. The result below is deterministic and does not claim any speedup from such a small workload.

Run the code

Run this example locally with Node.js. The exact sources are reviewed on Node 22.15.1 and Node 24.22.1 unless a specialised lab states otherwise. Save the complete source as worker-threads.mjs in a separate empty exercises folder and run node worker-threads.mjs. There is no Node.js browser runner on Bhylu; the plain JavaScript playground does not provide these filesystem, server or process APIs.

Download the complete source. Ordinary Node scripts need no Apache, PHP or MySQL service. File examples own their temporary folders; network fixtures use loopback and available temporary ports.

Example

worker-threads.mjs

import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
import { once } from 'node:events';
if (isMainThread) {
  const worker = new Worker(new URL(import.meta.url), {
    workerData: [3, 2, 0],
    resourceLimits: { maxOldGenerationSizeMb: 32 },
  });
  const exited = once(worker, 'exit');
  const [result] = await once(worker, 'message');
  const [status] = await exited;
  console.log(result, status);
} else {
  parentPort.postMessage(workerData.reduce((sum, value) => sum + value, 0));
}

Expected result

5 0

The parent receives the computed sum and a successful worker exit. Worker resource limits apply to specified runtime resources; they do not turn the shared process into a safe public execution service or cap every native allocation.

Use the Node.js API reference for the precise version contract.