new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Bun · Runtime · all subjects

bun apis/workers

22 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Worker API: new Worker()

Bun supports Web Workers through the new Worker() constructor for multi-threaded/concurrent operations.

Worker constructor basic usage

Create a worker by calling `new Worker(specifier)` where specifier is a file path or blob URL. Example: `const worker = new Worker('./worker.ts');` Specifiers are resolved relative to the project root.

Worker supports TypeScript JSX and TSX without build step

Bun's Worker implementation supports CommonJS, ES modules, TypeScript, JSX, and TSX with no extra build step required.

Prevent TypeScript errors with self in worker

Add `declare var self: Worker;` at the top of worker files to prevent TypeScript errors when using the global `self` object.

Worker error handling for failed script resolution

If a worker's script fails to resolve, an 'error' event is emitted on the Worker object. Attach an error listener with `worker.addEventListener('error', event => {...});` to handle resolution failures.

Worker preload option loads modules before worker starts

Pass `preload` option to Worker constructor to load modules before the worker's own code runs. Accepts array of strings or single string. Example: `new Worker('./worker.ts', { preload: ['./load-sentry.js'] })` or `new Worker('./worker.ts', { preload: './load-sentry.js' })`

Create worker from blob URL

Pass a blob: URL to Worker constructor to create a worker from in-memory source. Set the Blob's type property to 'application/typescript' for TypeScript files, or pass a filename to File constructor. Example: `const blob = new Blob([code], { type: 'application/typescript' }); const url = URL.createObjectURL(blob); const worker = new Worker(url);`

Worker 'open' event signals worker ready for messages

The 'open' event is emitted when a worker is created and ready to receive messages. This event does not exist in browsers. Bun enqueues messages until the worker is ready, so you don't need to wait for 'open' before sending messages.

postMessage for worker communication

Use `worker.postMessage(data)` on main thread and `postMessage(data)` or `self.postMessage(data)` on worker thread to send messages. Messages are serialized with the HTML Structured Clone Algorithm. On the worker thread, `postMessage` is automatically routed to the parent thread.

Worker postMessage string fast path optimization

When posting a pure string with postMessage, Bun bypasses the structured clone algorithm entirely, eliminating serialization overhead.

Worker postMessage simple object fast path optimization

For plain objects containing only primitive values, Bun stores properties directly without full structured cloning. Fast path activates when: object is plain with no prototype chain modifications; contains only enumerable configurable data properties; has no indexed properties or getter/setter methods; all property values are primitives or strings. This makes postMessage 2-241x faster.

Listen to worker messages with message event

Receive messages on worker thread with `self.addEventListener('message', event => {...})` or `self.onmessage = fn`. On main thread use `worker.addEventListener('message', event => {...})` or `worker.onmessage = fn`. Access message data with `event.data`.

Terminate worker with terminate() method

Call `worker.terminate()` to forcefully terminate a Worker. The Worker instance terminates automatically once its event loop has no work left to do. Attaching a 'message' listener on the global or any MessagePorts keeps the event loop alive.

Worker self-termination with process.exit()

A worker can terminate itself with `process.exit()`. This does not terminate the main process. Like in Node.js, `process.on('beforeExit', callback)` and `process.on('exit', callback)` are emitted on the worker thread (not main thread), and exit code is passed to the 'close' event.

Worker 'close' event signals termination completion

The 'close' event is emitted when a worker has been marked as terminated; the worker itself can take some time to fully exit. The CloseEvent contains the exit code passed to process.exit(), or 0 if closed for another reason. This event does not exist in browsers.

Worker unref() decouples worker lifetime from main process

Call `worker.unref()` to stop an active worker from keeping the main process alive. This decouples the worker's lifetime from the main process's, matching Node.js worker_threads behavior. `unref()` is not available in browsers.

Worker ref() keeps process alive until worker terminates

Call `worker.ref()` to keep the main process alive until the Worker terminates. Workers are ref'd by default; a ref'd worker still needs something on its event loop (like a 'message' listener) to continue running. Can also pass `ref: false` in options to Worker constructor.

Worker smol mode reduces memory usage

Pass `smol: true` in the Worker constructor's options object to enable smol mode, which reduces memory usage at a cost of performance. Setting `smol: true` sets `JSC::HeapSize` to be `Small` instead of the default `Large`.

Share data between main thread and workers with setEnvironmentData and getEnvironmentData

Use `setEnvironmentData(key, value)` on main thread and `getEnvironmentData(key)` in worker to share data. Import from 'worker_threads' module. Example: `import { setEnvironmentData, getEnvironmentData } from 'worker_threads'; setEnvironmentData('config', { apiUrl: 'https://api.example.com' }); const config = getEnvironmentData('config');`

Listen for worker creation events with process.on

Use `process.on('worker', worker => {...})` to listen for worker creation events. The callback receives the worker with threadId property.

Bun.isMainThread checks if on main thread

Check `Bun.isMainThread` boolean to determine whether code is running on the main thread or in a worker. Returns true if on main thread, false if in a worker.

Worker API is experimental

The Worker API is still experimental, particularly for terminating workers. Bun is actively working on improvements.

Give your agent this brain