Browse packages

Package · v0.17.1

worker

Standard library workers

Portable Web Workers for JavaScript runtimes.

Installation#

bash
npm install @rcompat/worker
bash
pnpm add @rcompat/worker
bash
yarn add @rcompat/worker
bash
bun add @rcompat/worker

Usage#

js
import Worker from "@rcompat/worker";

const worker = new Worker(new URL("./worker.js", import.meta.url), {
  name: "example",
});

worker.addEventListener("message", event => {
  console.log(event.data);
});
worker.postMessage("hello");

The package exposes the Web Worker interface in browsers, Bun, Deno, and Node. Node workers are bootstrapped with self, postMessage, onmessage, and the standard event-target methods so the same module worker can run in every supported runtime.

Workers are always ES modules. The optional second argument has the shared WorkerOptions shape { name?: string; type?: "module" }; module mode is the default, so type can normally be omitted.

The portable interface includes:

  • postMessage(message, transfer?)
  • addEventListener() and removeEventListener()
  • onmessage, onmessageerror, and onerror
  • terminate()

The package also exports the type-only Worker, WorkerConstructor, and WorkerOptions contracts from its root. It has no runtime subpath exports.

Worker scripts should use the Web Worker messaging API rather than runtime-specific APIs such as Node's parentPort.