Creating a Worker
worker.ts:
Worker Options
Module Type
Workers can be ES modules or classic scripts:Worker Name
Name workers for debugging:Credentials
Control credential passing for module imports:Communication
Posting Messages
Send data between main thread and worker:Message Event
Error Handling
Unhandled Rejections
Transferring Data
Structured Clone
By default, data is cloned:- Primitives (string, number, boolean)
- Objects and Arrays
Date,RegExp,Map,SetArrayBuffer,TypedArraysBlob,File,ImageData
Transfer Objects
For better performance, transfer ownership:ArrayBufferMessagePortReadableStreamWritableStreamTransformStream
Shared Memory
UseSharedArrayBuffer for shared memory:
Worker Lifecycle
Terminating Workers
Reference Counting
Control whether worker keeps process alive:Worker Scope
Global Objects
Inside a worker:Available APIs
Workers have access to:consolesetTimeout,setInterval,setImmediatefetch,WebSocketcrypto,TextEncoder,TextDecoderURL,URLSearchParamsBlob,File,FormDataReadableStream,WritableStream- Import maps and ES modules
Not Available
- DOM APIs (document, window)
- Most Bun-specific APIs (Bun.serve, etc.)
- Process-level APIs (process.exit)
Import Maps in Workers
Workers support import maps:TypeScript
Bun automatically transpiles TypeScript in workers:Nested Workers
Workers can create other workers:Common Patterns
Worker Pool
Request-Response Pattern
Progress Updates
Performance Considerations
When to Use Workers
Good use cases:- CPU-intensive computations
- Parsing large data files
- Image/video processing
- Cryptographic operations
- Parallel data processing
- I/O operations (use async instead)
- Simple computations (overhead not worth it)
- DOM manipulation (not available in workers)
Minimizing Communication
Message passing has overhead:Using Transfers
Transfer large buffers instead of cloning:Debugging Workers
Compatibility
Bun’s Web Workers are compatible with:- Browsers (Chrome, Firefox, Safari, Edge)
- Deno
- Cloudflare Workers (with some limitations)
Differences from Node.js
Bun implements the standard Web Workers API, not Node.jsworker_threads:
- Use
postMessageinstead ofparentPort.postMessage - Use
self.onmessageinstead ofparentPort.on('message') - No
workerData- pass data viapostMessage