Skip to content

node:worker_threads

How Elide supports Node's worker_threads: Worker, parentPort, MessageChannel and the other exports, which Worker options it reads, and other differences.

On this page

node:worker_threads runs scripts on separate threads with Node’s worker_threads API. elide run does not exit while a worker runs.

Example

js
// worker.mjs
import { Worker } from "node:worker_threads";

const source = `
  const { parentPort, workerData } = require("node:worker_threads");
  parentPort.postMessage(workerData.map((n) => n * n));
`;
const worker = new Worker(source, { eval: true, workerData: [1, 2, 3] });
worker.on("message", (squares) => {
  console.log("from worker:", squares.join(" "));
  worker.terminate();
});
worker.on("exit", (code) => console.log("worker exited", code));
utf-8 · js · Lines: 13

elide run worker.mjs prints:

text
from worker: 1 4 9
worker exited 0
utf-8 · text · Lines: 2

Differences from Node

  • new Worker reads only the workerData, eval, transferList, and env options.
  • A missing script file emits error with code ERR_WORKER_PATH.
  • stdout and stderr are always inherited from the parent.
  • resourceLimits is {}.
  • Posting a ReadableStream throws DataCloneError.
  • Posting to a terminated worker is a no-op.
  • --limit=workers=COUNT limits how many workers a script may start; see Sandbox.

Samples

Reference

Status: Partial · 105 of 128 suite tests pass (82.0%)

worker_threads exports

BroadcastChannel, MessageChannel, MessagePort, Worker, getEnvironmentData, isInternalThread, isMainThread, isMarkedAsUntransferable, markAsUncloneable, markAsUntransferable, moveMessagePortToContext, parentPort, postMessageToThread, receiveMessageOnPort, resourceLimits, setEnvironmentData, threadId, threadName, workerData, 1 constants such as SHARE_ENV

Not implemented

locks.

Tests: node-api node:worker-threads: 105 pass, 22 fail, 1 error, 11 skipped. Failing: test-worker-cleanup-handles.js, test-worker-cpu-profile.js, test-worker-data-url.js, test-worker-eval-typescript.js, test-worker-exit-heapsnapshot.js, test-worker-heap-profile.js, test-worker-heap-snapshot.js, test-worker-heapdump-failure.js, and 15 more.

Was this page helpful?