bun-types 1.3.2-canary.20251106T140813 → 1.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bun.d.ts +102 -6
- package/docs/bundler/bytecode.mdx +465 -0
- package/docs/bundler/css.mdx +1024 -0
- package/docs/bundler/esbuild.mdx +253 -0
- package/docs/bundler/executables.mdx +535 -0
- package/docs/bundler/fullstack.mdx +1064 -0
- package/docs/bundler/hot-reloading.mdx +229 -0
- package/docs/bundler/html-static.mdx +386 -0
- package/docs/bundler/index.mdx +1499 -0
- package/docs/bundler/loaders.mdx +356 -0
- package/docs/bundler/macros.mdx +328 -0
- package/docs/bundler/minifier.mdx +1306 -0
- package/docs/bundler/plugins.mdx +411 -0
- package/docs/feedback.mdx +85 -0
- package/docs/guides/binary/arraybuffer-to-array.mdx +29 -0
- package/docs/guides/binary/arraybuffer-to-blob.mdx +26 -0
- package/docs/guides/binary/arraybuffer-to-buffer.mdx +27 -0
- package/docs/guides/binary/arraybuffer-to-string.mdx +17 -0
- package/docs/guides/binary/arraybuffer-to-typedarray.mdx +41 -0
- package/docs/guides/binary/blob-to-arraybuffer.mdx +16 -0
- package/docs/guides/binary/blob-to-dataview.mdx +16 -0
- package/docs/guides/binary/blob-to-stream.mdx +16 -0
- package/docs/guides/binary/blob-to-string.mdx +17 -0
- package/docs/guides/binary/blob-to-typedarray.mdx +16 -0
- package/docs/guides/binary/buffer-to-arraybuffer.mdx +16 -0
- package/docs/guides/binary/buffer-to-blob.mdx +16 -0
- package/docs/guides/binary/buffer-to-readablestream.mdx +43 -0
- package/docs/guides/binary/buffer-to-string.mdx +27 -0
- package/docs/guides/binary/buffer-to-typedarray.mdx +16 -0
- package/docs/guides/binary/dataview-to-string.mdx +17 -0
- package/docs/guides/binary/typedarray-to-arraybuffer.mdx +27 -0
- package/docs/guides/binary/typedarray-to-blob.mdx +18 -0
- package/docs/guides/binary/typedarray-to-buffer.mdx +16 -0
- package/docs/guides/binary/typedarray-to-dataview.mdx +16 -0
- package/docs/guides/binary/typedarray-to-readablestream.mdx +43 -0
- package/docs/guides/binary/typedarray-to-string.mdx +18 -0
- package/docs/guides/deployment/aws-lambda.mdx +204 -0
- package/docs/guides/deployment/digital-ocean.mdx +161 -0
- package/docs/guides/deployment/google-cloud-run.mdx +197 -0
- package/docs/guides/deployment/railway.mdx +145 -0
- package/docs/guides/deployment/render.mdx +82 -0
- package/docs/guides/deployment/vercel.mdx +99 -0
- package/docs/guides/ecosystem/astro.mdx +82 -0
- package/docs/guides/ecosystem/discordjs.mdx +80 -0
- package/docs/guides/ecosystem/docker.mdx +151 -0
- package/docs/guides/ecosystem/drizzle.mdx +195 -0
- package/docs/guides/ecosystem/edgedb.mdx +257 -0
- package/docs/guides/ecosystem/elysia.mdx +31 -0
- package/docs/guides/ecosystem/express.mdx +43 -0
- package/docs/guides/ecosystem/hono.mdx +47 -0
- package/docs/guides/ecosystem/mongoose.mdx +92 -0
- package/docs/guides/ecosystem/neon-drizzle.mdx +234 -0
- package/docs/guides/ecosystem/neon-serverless-postgres.mdx +60 -0
- package/docs/guides/ecosystem/nextjs.mdx +57 -0
- package/docs/guides/ecosystem/nuxt.mdx +90 -0
- package/docs/guides/ecosystem/pm2.mdx +55 -0
- package/docs/guides/ecosystem/prisma-postgres.mdx +169 -0
- package/docs/guides/ecosystem/prisma.mdx +164 -0
- package/docs/guides/ecosystem/qwik.mdx +114 -0
- package/docs/guides/ecosystem/react.mdx +52 -0
- package/docs/guides/ecosystem/remix.mdx +97 -0
- package/docs/guides/ecosystem/sentry.mdx +54 -0
- package/docs/guides/ecosystem/solidstart.mdx +66 -0
- package/docs/guides/ecosystem/ssr-react.mdx +49 -0
- package/docs/guides/ecosystem/stric.mdx +54 -0
- package/docs/guides/ecosystem/sveltekit.mdx +138 -0
- package/docs/guides/ecosystem/systemd.mdx +114 -0
- package/docs/guides/ecosystem/upstash.mdx +87 -0
- package/docs/guides/ecosystem/vite.mdx +77 -0
- package/docs/guides/html-rewriter/extract-links.mdx +72 -0
- package/docs/guides/html-rewriter/extract-social-meta.mdx +97 -0
- package/docs/guides/http/cluster.mdx +69 -0
- package/docs/guides/http/fetch-unix.mdx +35 -0
- package/docs/guides/http/fetch.mdx +26 -0
- package/docs/guides/http/file-uploads.mdx +97 -0
- package/docs/guides/http/hot.mdx +28 -0
- package/docs/guides/http/proxy.mdx +26 -0
- package/docs/guides/http/server.mdx +48 -0
- package/docs/guides/http/simple.mdx +20 -0
- package/docs/guides/http/stream-file.mdx +50 -0
- package/docs/guides/http/stream-iterator.mdx +49 -0
- package/docs/guides/http/stream-node-streams-in-bun.mdx +22 -0
- package/docs/guides/http/tls.mdx +32 -0
- package/docs/guides/index.mdx +10 -0
- package/docs/guides/install/add-dev.mdx +28 -0
- package/docs/guides/install/add-git.mdx +38 -0
- package/docs/guides/install/add-optional.mdx +27 -0
- package/docs/guides/install/add-peer.mdx +45 -0
- package/docs/guides/install/add-tarball.mdx +35 -0
- package/docs/guides/install/add.mdx +44 -0
- package/docs/guides/install/azure-artifacts.mdx +76 -0
- package/docs/guides/install/cicd.mdx +43 -0
- package/docs/guides/install/custom-registry.mdx +32 -0
- package/docs/guides/install/from-npm-install-to-bun-install.mdx +230 -0
- package/docs/guides/install/git-diff-bun-lockfile.mdx +47 -0
- package/docs/guides/install/jfrog-artifactory.mdx +28 -0
- package/docs/guides/install/npm-alias.mdx +25 -0
- package/docs/guides/install/registry-scope.mdx +40 -0
- package/docs/guides/install/trusted.mdx +50 -0
- package/docs/guides/install/workspaces.mdx +70 -0
- package/docs/guides/install/yarnlock.mdx +50 -0
- package/docs/guides/process/argv.mdx +66 -0
- package/docs/guides/process/ctrl-c.mdx +18 -0
- package/docs/guides/process/ipc.mdx +69 -0
- package/docs/guides/process/nanoseconds.mdx +15 -0
- package/docs/guides/process/os-signals.mdx +41 -0
- package/docs/guides/process/spawn-stderr.mdx +34 -0
- package/docs/guides/process/spawn-stdout.mdx +28 -0
- package/docs/guides/process/spawn.mdx +43 -0
- package/docs/guides/process/stdin.mdx +62 -0
- package/docs/guides/read-file/arraybuffer.mdx +30 -0
- package/docs/guides/read-file/buffer.mdx +21 -0
- package/docs/guides/read-file/exists.mdx +18 -0
- package/docs/guides/read-file/json.mdx +19 -0
- package/docs/guides/read-file/mime.mdx +22 -0
- package/docs/guides/read-file/stream.mdx +28 -0
- package/docs/guides/read-file/string.mdx +24 -0
- package/docs/guides/read-file/uint8array.mdx +23 -0
- package/docs/guides/read-file/watch.mdx +66 -0
- package/docs/guides/runtime/build-time-constants.mdx +295 -0
- package/docs/guides/runtime/cicd.mdx +45 -0
- package/docs/guides/runtime/codesign-macos-executable.mdx +61 -0
- package/docs/guides/runtime/define-constant.mdx +149 -0
- package/docs/guides/runtime/delete-directory.mdx +39 -0
- package/docs/guides/runtime/delete-file.mdx +21 -0
- package/docs/guides/runtime/heap-snapshot.mdx +28 -0
- package/docs/guides/runtime/import-html.mdx +17 -0
- package/docs/guides/runtime/import-json.mdx +46 -0
- package/docs/guides/runtime/import-toml.mdx +32 -0
- package/docs/guides/runtime/import-yaml.mdx +104 -0
- package/docs/guides/runtime/read-env.mdx +37 -0
- package/docs/guides/runtime/set-env.mdx +51 -0
- package/docs/guides/runtime/shell.mdx +42 -0
- package/docs/guides/runtime/timezone.mdx +38 -0
- package/docs/guides/runtime/tsconfig-paths.mdx +31 -0
- package/docs/guides/runtime/typescript.mdx +51 -0
- package/docs/guides/runtime/vscode-debugger.mdx +48 -0
- package/docs/guides/runtime/web-debugger.mdx +103 -0
- package/docs/guides/streams/node-readable-to-arraybuffer.mdx +13 -0
- package/docs/guides/streams/node-readable-to-blob.mdx +13 -0
- package/docs/guides/streams/node-readable-to-json.mdx +14 -0
- package/docs/guides/streams/node-readable-to-string.mdx +14 -0
- package/docs/guides/streams/node-readable-to-uint8array.mdx +13 -0
- package/docs/guides/streams/to-array.mdx +16 -0
- package/docs/guides/streams/to-arraybuffer.mdx +16 -0
- package/docs/guides/streams/to-blob.mdx +16 -0
- package/docs/guides/streams/to-buffer.mdx +17 -0
- package/docs/guides/streams/to-json.mdx +16 -0
- package/docs/guides/streams/to-string.mdx +16 -0
- package/docs/guides/streams/to-typedarray.mdx +24 -0
- package/docs/guides/test/bail.mdx +24 -0
- package/docs/guides/test/coverage-threshold.mdx +67 -0
- package/docs/guides/test/coverage.mdx +49 -0
- package/docs/guides/test/happy-dom.mdx +73 -0
- package/docs/guides/test/migrate-from-jest.mdx +125 -0
- package/docs/guides/test/mock-clock.mdx +50 -0
- package/docs/guides/test/mock-functions.mdx +70 -0
- package/docs/guides/test/rerun-each.mdx +16 -0
- package/docs/guides/test/run-tests.mdx +116 -0
- package/docs/guides/test/skip-tests.mdx +43 -0
- package/docs/guides/test/snapshot.mdx +102 -0
- package/docs/guides/test/spy-on.mdx +49 -0
- package/docs/guides/test/svelte-test.mdx +113 -0
- package/docs/guides/test/testing-library.mdx +93 -0
- package/docs/guides/test/timeout.mdx +17 -0
- package/docs/guides/test/todo-tests.mdx +74 -0
- package/docs/guides/test/update-snapshots.mdx +49 -0
- package/docs/guides/test/watch-mode.mdx +24 -0
- package/docs/guides/util/base64.mdx +17 -0
- package/docs/guides/util/deep-equals.mdx +41 -0
- package/docs/guides/util/deflate.mdx +20 -0
- package/docs/guides/util/detect-bun.mdx +25 -0
- package/docs/guides/util/entrypoint.mdx +19 -0
- package/docs/guides/util/escape-html.mdx +24 -0
- package/docs/guides/util/file-url-to-path.mdx +16 -0
- package/docs/guides/util/gzip.mdx +20 -0
- package/docs/guides/util/hash-a-password.mdx +56 -0
- package/docs/guides/util/import-meta-dir.mdx +15 -0
- package/docs/guides/util/import-meta-file.mdx +15 -0
- package/docs/guides/util/import-meta-path.mdx +15 -0
- package/docs/guides/util/javascript-uuid.mdx +25 -0
- package/docs/guides/util/main.mdx +43 -0
- package/docs/guides/util/path-to-file-url.mdx +16 -0
- package/docs/guides/util/sleep.mdx +24 -0
- package/docs/guides/util/version.mdx +23 -0
- package/docs/guides/util/which-path-to-executable-bin.mdx +17 -0
- package/docs/guides/websocket/compression.mdx +33 -0
- package/docs/guides/websocket/context.mdx +74 -0
- package/docs/guides/websocket/pubsub.mdx +40 -0
- package/docs/guides/websocket/simple.mdx +35 -0
- package/docs/guides/write-file/append.mdx +54 -0
- package/docs/guides/write-file/basic.mdx +46 -0
- package/docs/guides/write-file/blob.mdx +30 -0
- package/docs/guides/write-file/cat.mdx +19 -0
- package/docs/guides/write-file/file-cp.mdx +18 -0
- package/docs/guides/write-file/filesink.mdx +54 -0
- package/docs/guides/write-file/response.mdx +19 -0
- package/docs/guides/write-file/stdout.mdx +23 -0
- package/docs/guides/write-file/stream.mdx +19 -0
- package/docs/guides/write-file/unlink.mdx +18 -0
- package/docs/index.mdx +133 -0
- package/docs/installation.mdx +365 -0
- package/docs/pm/bunx.mdx +83 -0
- package/docs/pm/catalogs.mdx +292 -0
- package/docs/pm/cli/add.mdx +179 -0
- package/docs/pm/cli/audit.mdx +60 -0
- package/docs/pm/cli/install.mdx +471 -0
- package/docs/pm/cli/link.mdx +48 -0
- package/docs/pm/cli/outdated.mdx +197 -0
- package/docs/pm/cli/patch.mdx +69 -0
- package/docs/pm/cli/pm.mdx +319 -0
- package/docs/pm/cli/publish.mdx +123 -0
- package/docs/pm/cli/remove.mdx +16 -0
- package/docs/pm/cli/update.mdx +140 -0
- package/docs/pm/cli/why.mdx +84 -0
- package/docs/pm/filter.mdx +102 -0
- package/docs/pm/global-cache.mdx +72 -0
- package/docs/pm/isolated-installs.mdx +205 -0
- package/docs/pm/lifecycle.mdx +57 -0
- package/docs/pm/lockfile.mdx +64 -0
- package/docs/pm/npmrc.mdx +111 -0
- package/docs/pm/overrides.mdx +83 -0
- package/docs/pm/scopes-registries.mdx +35 -0
- package/docs/pm/security-scanner-api.mdx +95 -0
- package/docs/pm/workspaces.mdx +109 -0
- package/docs/project/benchmarking.mdx +218 -0
- package/docs/project/bindgen.mdx +223 -0
- package/docs/project/building-windows.mdx +133 -0
- package/docs/project/contributing.mdx +343 -0
- package/docs/project/feedback.mdx +20 -0
- package/docs/project/license.mdx +78 -0
- package/docs/project/roadmap.mdx +8 -0
- package/docs/quickstart.mdx +240 -0
- package/docs/runtime/auto-install.mdx +97 -0
- package/docs/runtime/binary-data.mdx +846 -0
- package/docs/runtime/bun-apis.mdx +59 -0
- package/docs/runtime/bunfig.mdx +642 -0
- package/docs/runtime/c-compiler.mdx +204 -0
- package/docs/runtime/child-process.mdx +532 -0
- package/docs/runtime/color.mdx +267 -0
- package/docs/runtime/console.mdx +67 -0
- package/docs/runtime/cookies.mdx +454 -0
- package/docs/runtime/debugger.mdx +335 -0
- package/docs/runtime/environment-variables.mdx +214 -0
- package/docs/runtime/ffi.mdx +565 -0
- package/docs/runtime/file-io.mdx +306 -0
- package/docs/runtime/file-system-router.mdx +118 -0
- package/docs/runtime/file-types.mdx +354 -0
- package/docs/runtime/glob.mdx +181 -0
- package/docs/runtime/globals.mdx +72 -0
- package/docs/runtime/hashing.mdx +315 -0
- package/docs/runtime/html-rewriter.mdx +340 -0
- package/docs/runtime/http/cookies.mdx +79 -0
- package/docs/runtime/http/error-handling.mdx +40 -0
- package/docs/runtime/http/metrics.mdx +36 -0
- package/docs/runtime/http/routing.mdx +289 -0
- package/docs/runtime/http/server.mdx +647 -0
- package/docs/runtime/http/tls.mdx +101 -0
- package/docs/runtime/http/websockets.mdx +404 -0
- package/docs/runtime/index.mdx +223 -0
- package/docs/runtime/jsx.mdx +115 -0
- package/docs/runtime/module-resolution.mdx +342 -0
- package/docs/runtime/networking/dns.mdx +111 -0
- package/docs/runtime/networking/fetch.mdx +468 -0
- package/docs/runtime/networking/tcp.mdx +239 -0
- package/docs/runtime/networking/udp.mdx +129 -0
- package/docs/runtime/node-api.mdx +19 -0
- package/docs/runtime/nodejs-compat.mdx +468 -0
- package/docs/runtime/plugins.mdx +405 -0
- package/docs/runtime/redis.mdx +582 -0
- package/docs/runtime/s3.mdx +863 -0
- package/docs/runtime/secrets.mdx +336 -0
- package/docs/runtime/semver.mdx +57 -0
- package/docs/runtime/shell.mdx +637 -0
- package/docs/runtime/sql.mdx +1404 -0
- package/docs/runtime/sqlite.mdx +699 -0
- package/docs/runtime/streams.mdx +232 -0
- package/docs/runtime/templating/create.mdx +269 -0
- package/docs/runtime/templating/init.mdx +58 -0
- package/docs/runtime/transpiler.mdx +288 -0
- package/docs/runtime/typescript.mdx +58 -0
- package/docs/runtime/utils.mdx +922 -0
- package/docs/runtime/watch-mode.mdx +161 -0
- package/docs/runtime/web-apis.mdx +29 -0
- package/docs/runtime/workers.mdx +328 -0
- package/docs/runtime/yaml.mdx +469 -0
- package/docs/snippets/cli/add.mdx +166 -0
- package/docs/snippets/cli/build.mdx +196 -0
- package/docs/snippets/cli/feedback.mdx +17 -0
- package/docs/snippets/cli/init.mdx +84 -0
- package/docs/snippets/cli/install.mdx +173 -0
- package/docs/snippets/cli/link.mdx +163 -0
- package/docs/snippets/cli/outdated.mdx +140 -0
- package/docs/snippets/cli/patch.mdx +171 -0
- package/docs/snippets/cli/publish.mdx +198 -0
- package/docs/snippets/cli/remove.mdx +146 -0
- package/docs/snippets/cli/run.mdx +293 -0
- package/docs/snippets/cli/test.mdx +100 -0
- package/docs/snippets/cli/update.mdx +144 -0
- package/docs/snippets/product-card.mdx +32 -0
- package/docs/snippets/product-tiles.mdx +94 -0
- package/docs/test/code-coverage.mdx +409 -0
- package/docs/test/configuration.mdx +467 -0
- package/docs/test/dates-times.mdx +129 -0
- package/docs/test/discovery.mdx +90 -0
- package/docs/test/dom.mdx +226 -0
- package/docs/test/index.mdx +380 -0
- package/docs/test/lifecycle.mdx +348 -0
- package/docs/test/mocks.mdx +637 -0
- package/docs/test/reporters.mdx +117 -0
- package/docs/test/runtime-behavior.mdx +342 -0
- package/docs/test/snapshots.mdx +434 -0
- package/docs/test/writing-tests.mdx +635 -0
- package/docs/typescript.mdx +54 -0
- package/package.json +8 -6
- package/test.d.ts +2 -2
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: "Watch Mode"
|
|
3
|
+
description: "Automatic reloading in Bun with --watch and --hot modes"
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
Bun supports two kinds of automatic reloading via CLI flags:
|
|
7
|
+
|
|
8
|
+
- `--watch` mode, which hard restarts Bun's process when imported files change.
|
|
9
|
+
- `--hot` mode, which soft reloads the code (without restarting the process) when imported files change.
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## `--watch` mode
|
|
14
|
+
|
|
15
|
+
Watch mode can be used with `bun test` or when running TypeScript, JSX, and JavaScript files.
|
|
16
|
+
|
|
17
|
+
To run a file in `--watch` mode:
|
|
18
|
+
|
|
19
|
+
```bash terminal icon="terminal"
|
|
20
|
+
bun --watch index.tsx
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
To run your tests in `--watch` mode:
|
|
24
|
+
|
|
25
|
+
```bash terminal icon="terminal"
|
|
26
|
+
bun --watch test
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
In `--watch` mode, Bun keeps track of all imported files and watches them for changes. When a change is detected, Bun restarts the process, preserving the same set of CLI arguments and environment variables used in the initial run. If Bun crashes, `--watch` will attempt to automatically restart the process.
|
|
30
|
+
|
|
31
|
+
<Note>
|
|
32
|
+
|
|
33
|
+
**⚡️ Reloads are fast.** The filesystem watchers you're probably used to have several layers of libraries wrapping the native APIs or worse, rely on polling.
|
|
34
|
+
|
|
35
|
+
Instead, Bun uses operating system native filesystem watcher APIs like kqueue or inotify to detect changes to files. Bun also does a number of optimizations to enable it scale to larger projects (such as setting a high rlimit for file descriptors, statically allocated file path buffers, reuse file descriptors when possible, etc).
|
|
36
|
+
|
|
37
|
+
</Note>
|
|
38
|
+
|
|
39
|
+
The following examples show Bun live-reloading a file as it is edited, with VSCode configured to save the file [on each keystroke](https://code.visualstudio.com/docs/editor/codebasics#_save-auto-save).
|
|
40
|
+
|
|
41
|
+
```sh terminal icon="terminal"
|
|
42
|
+
bun run --watch watchy.tsx
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
```tsx title="watchy.tsx" icon="/icons/typescript.svg"
|
|
46
|
+
import { serve } from "bun";
|
|
47
|
+
|
|
48
|
+
console.log("I restarted at:", Date.now());
|
|
49
|
+
|
|
50
|
+
serve({
|
|
51
|
+
port: 4003,
|
|
52
|
+
fetch(request) {
|
|
53
|
+
return new Response("Sup");
|
|
54
|
+
},
|
|
55
|
+
});
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
In this example, Bun is
|
|
59
|
+
|
|
60
|
+
<Frame>
|
|
61
|
+

|
|
62
|
+
</Frame>
|
|
63
|
+
|
|
64
|
+
Running `bun test` in watch mode and `save-on-keypress` enabled:
|
|
65
|
+
|
|
66
|
+
```bash terminal icon="terminal"
|
|
67
|
+
bun --watch test
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
<Frame>
|
|
71
|
+

|
|
72
|
+
</Frame>
|
|
73
|
+
|
|
74
|
+
<Note>
|
|
75
|
+
The **`--no-clear-screen`** flag is useful in scenarios where you don't want the terminal to clear, such as when
|
|
76
|
+
running multiple `bun build --watch` commands simultaneously using tools like `concurrently`. Without this flag, the
|
|
77
|
+
output of one instance could clear the output of others, potentially hiding errors from one instance beneath the
|
|
78
|
+
output of another. The `--no-clear-screen` flag, similar to TypeScript's `--preserveWatchOutput`, prevents this issue.
|
|
79
|
+
It can be used in combination with `--watch`, for example: `bun build --watch --no-clear-screen`.
|
|
80
|
+
</Note>
|
|
81
|
+
|
|
82
|
+
---
|
|
83
|
+
|
|
84
|
+
## `--hot` mode
|
|
85
|
+
|
|
86
|
+
Use `bun --hot` to enable hot reloading when executing code with Bun. This is distinct from `--watch` mode in that Bun does not hard-restart the entire process. Instead, it detects code changes and updates its internal module cache with the new code.
|
|
87
|
+
|
|
88
|
+
<Note>
|
|
89
|
+
This is not the same as hot reloading in the browser! Many frameworks provide a "hot reloading" experience, where you
|
|
90
|
+
can edit & save your frontend code (say, a React component) and see the changes reflected in the browser without
|
|
91
|
+
refreshing the page. Bun's `--hot` is the server-side equivalent of this experience. To get hot reloading in the
|
|
92
|
+
browser, use a framework like [Vite](https://vitejs.dev).
|
|
93
|
+
</Note>
|
|
94
|
+
|
|
95
|
+
```bash terminal icon="terminal"
|
|
96
|
+
bun --hot server.ts
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Starting from the entrypoint (`server.ts` in the example above), Bun builds a registry of all imported source files (excluding those in `node_modules`) and watches them for changes. When a change is detected, Bun performs a "soft reload". All files are re-evaluated, but all global state (notably, the `globalThis` object) is persisted.
|
|
100
|
+
|
|
101
|
+
```ts title="server.ts" icon="/icons/typescript.svg"
|
|
102
|
+
// make TypeScript happy
|
|
103
|
+
declare global {
|
|
104
|
+
var count: number;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
globalThis.count ??= 0;
|
|
108
|
+
console.log(`Reloaded ${globalThis.count} times`);
|
|
109
|
+
globalThis.count++;
|
|
110
|
+
|
|
111
|
+
// prevent `bun run` from exiting
|
|
112
|
+
setInterval(function () {}, 1000000);
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
If you run this file with `bun --hot server.ts`, you'll see the reload count increment every time you save the file.
|
|
116
|
+
|
|
117
|
+
```bash terminal icon="terminal"
|
|
118
|
+
bun --hot index.ts
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
```txt
|
|
122
|
+
Reloaded 1 times
|
|
123
|
+
Reloaded 2 times
|
|
124
|
+
Reloaded 3 times
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
Traditional file watchers like `nodemon` restart the entire process, so HTTP servers and other stateful objects are lost. By contrast, `bun --hot` is able to reflect the updated code without restarting the process.
|
|
128
|
+
|
|
129
|
+
### HTTP servers
|
|
130
|
+
|
|
131
|
+
This makes it possible, for instance, to update your HTTP request handler without shutting down the server itself. When you save the file, your HTTP server will be reloaded with the updated code without the process being restarted. This results in seriously fast refresh speeds.
|
|
132
|
+
|
|
133
|
+
```ts title="server.ts" icon="/icons/typescript.svg"
|
|
134
|
+
globalThis.count ??= 0;
|
|
135
|
+
globalThis.count++;
|
|
136
|
+
|
|
137
|
+
Bun.serve({
|
|
138
|
+
fetch(req: Request) {
|
|
139
|
+
return new Response(`Reloaded ${globalThis.count} times`);
|
|
140
|
+
},
|
|
141
|
+
port: 3000,
|
|
142
|
+
});
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
<Note>
|
|
146
|
+
**Note** — In a future version of Bun, support for Vite's `import.meta.hot` is planned to enable better lifecycle management for hot reloading and to align with the ecosystem.
|
|
147
|
+
|
|
148
|
+
</Note>
|
|
149
|
+
|
|
150
|
+
<Accordion title="Implementation details">
|
|
151
|
+
|
|
152
|
+
On hot reload, Bun:
|
|
153
|
+
|
|
154
|
+
- Resets the internal `require` cache and ES module registry (`Loader.registry`)
|
|
155
|
+
- Runs the garbage collector synchronously (to minimize memory leaks, at the cost of runtime performance)
|
|
156
|
+
- Re-transpiles all of your code from scratch (including sourcemaps)
|
|
157
|
+
- Re-evaluates the code with JavaScriptCore
|
|
158
|
+
|
|
159
|
+
This implementation isn't particularly optimized. It re-transpiles files that haven't changed. It makes no attempt at incremental compilation. It's a starting point.
|
|
160
|
+
|
|
161
|
+
</Accordion>
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: "Web APIs"
|
|
3
|
+
description: "Web-standard APIs supported by Bun for server-side JavaScript"
|
|
4
|
+
mode: center
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
Some Web APIs aren't relevant in the context of a server-first runtime like Bun, such as the [DOM API](https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API#html_dom_api_interfaces) or [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API). Many others, though, are broadly useful outside of the browser context; when possible, Bun implements these Web-standard APIs instead of introducing new APIs.
|
|
8
|
+
|
|
9
|
+
The following Web APIs are partially or completely supported.
|
|
10
|
+
|
|
11
|
+
| Category | APIs |
|
|
12
|
+
| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
13
|
+
| HTTP | [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/fetch), [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response), [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request), [`Headers`](https://developer.mozilla.org/en-US/docs/Web/API/Headers), [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController), [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) |
|
|
14
|
+
| URLs | [`URL`](https://developer.mozilla.org/en-US/docs/Web/API/URL), [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) |
|
|
15
|
+
| Web Workers | [`Worker`](https://developer.mozilla.org/en-US/docs/Web/API/Worker), [`self.postMessage`](https://developer.mozilla.org/en-US/docs/Web/API/DedicatedWorkerGlobalScope/postMessage), [`structuredClone`](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone), [`MessagePort`](https://developer.mozilla.org/en-US/docs/Web/API/MessagePort), [`MessageChannel`](https://developer.mozilla.org/en-US/docs/Web/API/MessageChannel), [`BroadcastChannel`](https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel) |
|
|
16
|
+
| Streams | [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream), [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream), [`TransformStream`](https://developer.mozilla.org/en-US/docs/Web/API/TransformStream), [`ByteLengthQueuingStrategy`](https://developer.mozilla.org/en-US/docs/Web/API/ByteLengthQueuingStrategy), [`CountQueuingStrategy`](https://developer.mozilla.org/en-US/docs/Web/API/CountQueuingStrategy) and associated classes |
|
|
17
|
+
| Blob | [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) |
|
|
18
|
+
| WebSockets | [`WebSocket`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) |
|
|
19
|
+
| Encoding and decoding | [`atob`](https://developer.mozilla.org/en-US/docs/Web/API/atob), [`btoa`](https://developer.mozilla.org/en-US/docs/Web/API/btoa), [`TextEncoder`](https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder), [`TextDecoder`](https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder) |
|
|
20
|
+
| JSON | [`JSON`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON) |
|
|
21
|
+
| Timeouts | [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout), [`clearTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/clearTimeout) |
|
|
22
|
+
| Intervals | [`setInterval`](https://developer.mozilla.org/en-US/docs/Web/API/setInterval), [`clearInterval`](https://developer.mozilla.org/en-US/docs/Web/API/clearInterval) |
|
|
23
|
+
| Crypto | [`crypto`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto), [`SubtleCrypto`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto), [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey) |
|
|
24
|
+
| Debugging | [`console`](https://developer.mozilla.org/en-US/docs/Web/API/console), [`performance`](https://developer.mozilla.org/en-US/docs/Web/API/Performance) |
|
|
25
|
+
| Microtasks | [`queueMicrotask`](https://developer.mozilla.org/en-US/docs/Web/API/queueMicrotask) |
|
|
26
|
+
| Errors | [`reportError`](https://developer.mozilla.org/en-US/docs/Web/API/reportError) |
|
|
27
|
+
| User interaction | [`alert`](https://developer.mozilla.org/en-US/docs/Web/API/Window/alert), [`confirm`](https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm), [`prompt`](https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt) (intended for interactive CLIs) |
|
|
28
|
+
| Realms | [`ShadowRealm`](https://github.com/tc39/proposal-shadowrealm) |
|
|
29
|
+
| Events | [`EventTarget`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget), [`Event`](https://developer.mozilla.org/en-US/docs/Web/API/Event), [`ErrorEvent`](https://developer.mozilla.org/en-US/docs/Web/API/ErrorEvent), [`CloseEvent`](https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent), [`MessageEvent`](https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent) |
|
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Workers
|
|
3
|
+
description: Use Bun's Workers API to create and communicate with a new JavaScript instance running on a separate thread while sharing I/O resources with the main thread
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
<Warning>
|
|
7
|
+
The `Worker` API is still experimental (particularly for terminating workers). We are actively working on improving
|
|
8
|
+
this.
|
|
9
|
+
</Warning>
|
|
10
|
+
|
|
11
|
+
[`Worker`](https://developer.mozilla.org/en-US/docs/Web/API/Worker) lets you start and communicate with a new JavaScript instance running on a separate thread while sharing I/O resources with the main thread.
|
|
12
|
+
|
|
13
|
+
Bun implements a minimal version of the [Web Workers API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) with extensions that make it work better for server-side use cases. Like the rest of Bun, `Worker` in Bun support CommonJS, ES Modules, TypeScript, JSX, TSX and more out of the box. No extra build steps are necessary.
|
|
14
|
+
|
|
15
|
+
## Creating a `Worker`
|
|
16
|
+
|
|
17
|
+
Like in browsers, [`Worker`](https://developer.mozilla.org/en-US/docs/Web/API/Worker) is a global. Use it to create a new worker thread.
|
|
18
|
+
|
|
19
|
+
### From the main thread
|
|
20
|
+
|
|
21
|
+
```ts index.ts icon="/icons/typescript.svg"
|
|
22
|
+
const worker = new Worker("./worker.ts");
|
|
23
|
+
|
|
24
|
+
worker.postMessage("hello");
|
|
25
|
+
worker.onmessage = event => {
|
|
26
|
+
console.log(event.data);
|
|
27
|
+
};
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
### Worker thread
|
|
31
|
+
|
|
32
|
+
```ts worker.ts icon="file-code"
|
|
33
|
+
// prevents TS errors
|
|
34
|
+
declare var self: Worker;
|
|
35
|
+
|
|
36
|
+
self.onmessage = (event: MessageEvent) => {
|
|
37
|
+
console.log(event.data);
|
|
38
|
+
postMessage("world");
|
|
39
|
+
};
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
To prevent TypeScript errors when using `self`, add this line to the top of your worker file.
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
declare var self: Worker;
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
You can use `import` and `export` syntax in your worker code. Unlike in browsers, there's no need to specify `{type: "module"}` to use ES Modules.
|
|
49
|
+
|
|
50
|
+
To simplify error handling, the initial script to load is resolved at the time `new Worker(url)` is called.
|
|
51
|
+
|
|
52
|
+
```js
|
|
53
|
+
const worker = new Worker("/not-found.js");
|
|
54
|
+
// throws an error immediately
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
The specifier passed to `Worker` is resolved relative to the project root (like typing `bun ./path/to/file.js`).
|
|
58
|
+
|
|
59
|
+
### `preload` - load modules before the worker starts
|
|
60
|
+
|
|
61
|
+
You can pass an array of module specifiers to the `preload` option to load modules before the worker starts. This is useful when you want to ensure some code is always loaded before the application starts, like loading OpenTelemetry, Sentry, DataDog, etc.
|
|
62
|
+
|
|
63
|
+
```ts index.ts icon="/icons/typescript.svg"
|
|
64
|
+
const worker = new Worker("./worker.ts", {
|
|
65
|
+
preload: ["./load-sentry.js"],
|
|
66
|
+
});
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Like the `--preload` CLI argument, the `preload` option is processed before the worker starts.
|
|
70
|
+
|
|
71
|
+
You can also pass a single string to the `preload` option:
|
|
72
|
+
|
|
73
|
+
```ts index.ts icon="/icons/typescript.svg"
|
|
74
|
+
const worker = new Worker("./worker.ts", {
|
|
75
|
+
preload: "./load-sentry.js",
|
|
76
|
+
});
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
This feature was added in Bun v1.1.35.
|
|
80
|
+
|
|
81
|
+
### `blob:` URLs
|
|
82
|
+
|
|
83
|
+
As of Bun v1.1.13, you can also pass a `blob:` URL to `Worker`. This is useful for creating workers from strings or other sources.
|
|
84
|
+
|
|
85
|
+
```js
|
|
86
|
+
const blob = new Blob(
|
|
87
|
+
[
|
|
88
|
+
`
|
|
89
|
+
self.onmessage = (event: MessageEvent) => postMessage(event.data)`,
|
|
90
|
+
],
|
|
91
|
+
{
|
|
92
|
+
type: "application/typescript",
|
|
93
|
+
},
|
|
94
|
+
);
|
|
95
|
+
const url = URL.createObjectURL(blob);
|
|
96
|
+
const worker = new Worker(url);
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Like the rest of Bun, workers created from `blob:` URLs support TypeScript, JSX, and other file types out of the box. You can communicate it should be loaded via typescript either via `type` or by passing a `filename` to the `File` constructor.
|
|
100
|
+
|
|
101
|
+
```ts
|
|
102
|
+
const file = new File(
|
|
103
|
+
[
|
|
104
|
+
`
|
|
105
|
+
self.onmessage = (event: MessageEvent) => postMessage(event.data)`,
|
|
106
|
+
],
|
|
107
|
+
"worker.ts",
|
|
108
|
+
);
|
|
109
|
+
const url = URL.createObjectURL(file);
|
|
110
|
+
const worker = new Worker(url);
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
### `"open"`
|
|
114
|
+
|
|
115
|
+
The `"open"` event is emitted when a worker is created and ready to receive messages. This can be used to send an initial message to a worker once it's ready. (This event does not exist in browsers.)
|
|
116
|
+
|
|
117
|
+
```ts index.ts icon="/icons/typescript.svg"
|
|
118
|
+
const worker = new Worker(new URL("worker.ts", import.meta.url).href);
|
|
119
|
+
|
|
120
|
+
worker.addEventListener("open", () => {
|
|
121
|
+
console.log("worker is ready");
|
|
122
|
+
});
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
Messages are automatically enqueued until the worker is ready, so there is no need to wait for the `"open"` event to send messages.
|
|
126
|
+
|
|
127
|
+
## Messages with `postMessage`
|
|
128
|
+
|
|
129
|
+
To send messages, use [`worker.postMessage`](https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage) and [`self.postMessage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage). This leverages the [HTML Structured Clone Algorithm](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm).
|
|
130
|
+
|
|
131
|
+
### Performance optimizations
|
|
132
|
+
|
|
133
|
+
Bun includes optimized fast paths for `postMessage` to dramatically improve performance for common data types:
|
|
134
|
+
|
|
135
|
+
**String fast path** - When posting pure string values, Bun bypasses the structured clone algorithm entirely, achieving significant performance gains with no serialization overhead.
|
|
136
|
+
|
|
137
|
+
**Simple object fast path** - For plain objects containing only primitive values (strings, numbers, booleans, null, undefined), Bun uses an optimized serialization path that stores properties directly without full structured cloning.
|
|
138
|
+
|
|
139
|
+
The simple object fast path activates when the object:
|
|
140
|
+
|
|
141
|
+
- Is a plain object with no prototype chain modifications
|
|
142
|
+
- Contains only enumerable, configurable data properties
|
|
143
|
+
- Has no indexed properties or getter/setter methods
|
|
144
|
+
- All property values are primitives or strings
|
|
145
|
+
|
|
146
|
+
With these fast paths, Bun's `postMessage` performs **2-241x faster** because the message length no longer has a meaningful impact on performance.
|
|
147
|
+
|
|
148
|
+
**Bun (with fast paths):**
|
|
149
|
+
|
|
150
|
+
```ts
|
|
151
|
+
postMessage({ prop: 11 chars string, ...9 more props }) - 648ns
|
|
152
|
+
postMessage({ prop: 14 KB string, ...9 more props }) - 719ns
|
|
153
|
+
postMessage({ prop: 3 MB string, ...9 more props }) - 1.26µs
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
**Node.js v24.6.0 (for comparison):**
|
|
157
|
+
|
|
158
|
+
```js
|
|
159
|
+
postMessage({ prop: 11 chars string, ...9 more props }) - 1.19µs
|
|
160
|
+
postMessage({ prop: 14 KB string, ...9 more props }) - 2.69µs
|
|
161
|
+
postMessage({ prop: 3 MB string, ...9 more props }) - 304µs
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
```js
|
|
165
|
+
// String fast path - optimized
|
|
166
|
+
postMessage("Hello, worker!");
|
|
167
|
+
|
|
168
|
+
// Simple object fast path - optimized
|
|
169
|
+
postMessage({
|
|
170
|
+
message: "Hello",
|
|
171
|
+
count: 42,
|
|
172
|
+
enabled: true,
|
|
173
|
+
data: null,
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
// Complex objects still work but use standard structured clone
|
|
177
|
+
postMessage({
|
|
178
|
+
nested: { deep: { object: true } },
|
|
179
|
+
date: new Date(),
|
|
180
|
+
buffer: new ArrayBuffer(8),
|
|
181
|
+
});
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
```js
|
|
185
|
+
// On the worker thread, `postMessage` is automatically "routed" to the parent thread.
|
|
186
|
+
postMessage({ hello: "world" });
|
|
187
|
+
|
|
188
|
+
// On the main thread
|
|
189
|
+
worker.postMessage({ hello: "world" });
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
To receive messages, use the [`message` event handler](https://developer.mozilla.org/en-US/docs/Web/API/Worker/message_event) on the worker and main thread.
|
|
193
|
+
|
|
194
|
+
```js
|
|
195
|
+
// Worker thread:
|
|
196
|
+
self.addEventListener("message", event => {
|
|
197
|
+
console.log(event.data);
|
|
198
|
+
});
|
|
199
|
+
// or use the setter:
|
|
200
|
+
// self.onmessage = fn
|
|
201
|
+
|
|
202
|
+
// if on the main thread
|
|
203
|
+
worker.addEventListener("message", event => {
|
|
204
|
+
console.log(event.data);
|
|
205
|
+
});
|
|
206
|
+
// or use the setter:
|
|
207
|
+
// worker.onmessage = fn
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
## Terminating a worker
|
|
211
|
+
|
|
212
|
+
A `Worker` instance terminates automatically once it's event loop has no work left to do. Attaching a `"message"` listener on the global or any `MessagePort`s will keep the event loop alive. To forcefully terminate a `Worker`, call `worker.terminate()`.
|
|
213
|
+
|
|
214
|
+
```ts index.ts icon="/icons/typescript.svg"
|
|
215
|
+
const worker = new Worker(new URL("worker.ts", import.meta.url).href);
|
|
216
|
+
|
|
217
|
+
// ...some time later
|
|
218
|
+
worker.terminate();
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
This will cause the worker's to exit as soon as possible.
|
|
222
|
+
|
|
223
|
+
### `process.exit()`
|
|
224
|
+
|
|
225
|
+
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 (and not on the main thread), and the exit code is passed to the `"close"` event.
|
|
226
|
+
|
|
227
|
+
### `"close"`
|
|
228
|
+
|
|
229
|
+
The `"close"` event is emitted when a worker has been terminated. It can take some time for the worker to actually terminate, so this event is emitted when the worker has been marked as terminated. The `CloseEvent` will contain the exit code passed to `process.exit()`, or 0 if closed for other reasons.
|
|
230
|
+
|
|
231
|
+
```ts index.ts icon="/icons/typescript.svg"
|
|
232
|
+
const worker = new Worker(new URL("worker.ts", import.meta.url).href);
|
|
233
|
+
|
|
234
|
+
worker.addEventListener("close", event => {
|
|
235
|
+
console.log("worker is being closed");
|
|
236
|
+
});
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
This event does not exist in browsers.
|
|
240
|
+
|
|
241
|
+
## Managing lifetime
|
|
242
|
+
|
|
243
|
+
By default, an active `Worker` will keep the main (spawning) process alive, so async tasks like `setTimeout` and promises will keep the process alive. Attaching `message` listeners will also keep the `Worker` alive.
|
|
244
|
+
|
|
245
|
+
### `worker.unref()`
|
|
246
|
+
|
|
247
|
+
To stop a running worker from keeping the process alive, call `worker.unref()`. This decouples the lifetime of the worker to the lifetime of the main process, and is equivalent to what Node.js' `worker_threads` does.
|
|
248
|
+
|
|
249
|
+
```ts index.ts icon="/icons/typescript.svg"
|
|
250
|
+
const worker = new Worker(new URL("worker.ts", import.meta.url).href);
|
|
251
|
+
worker.unref();
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
Note: `worker.unref()` is not available in browsers.
|
|
255
|
+
|
|
256
|
+
### `worker.ref()`
|
|
257
|
+
|
|
258
|
+
To keep the process alive until the `Worker` terminates, call `worker.ref()`. A ref'd worker is the default behavior, and still needs something going on in the event loop (such as a `"message"` listener) for the worker to continue running.
|
|
259
|
+
|
|
260
|
+
```ts index.ts icon="/icons/typescript.svg"
|
|
261
|
+
const worker = new Worker(new URL("worker.ts", import.meta.url).href);
|
|
262
|
+
worker.unref();
|
|
263
|
+
// later...
|
|
264
|
+
worker.ref();
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
Alternatively, you can also pass an `options` object to `Worker`:
|
|
268
|
+
|
|
269
|
+
```ts index.ts icon="/icons/typescript.svg"
|
|
270
|
+
const worker = new Worker(new URL("worker.ts", import.meta.url).href, {
|
|
271
|
+
ref: false,
|
|
272
|
+
});
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
Note: `worker.ref()` is not available in browsers.
|
|
276
|
+
|
|
277
|
+
## Memory usage with `smol`
|
|
278
|
+
|
|
279
|
+
JavaScript instances can use a lot of memory. Bun's `Worker` supports a `smol` mode that reduces memory usage, at a cost of performance. To enable `smol` mode, pass `smol: true` to the `options` object in the `Worker` constructor.
|
|
280
|
+
|
|
281
|
+
```ts index.ts icon="/icons/typescript.svg"
|
|
282
|
+
const worker = new Worker("./i-am-smol.ts", {
|
|
283
|
+
smol: true,
|
|
284
|
+
});
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
<Accordion title="What does `smol` mode actually do?">
|
|
288
|
+
Setting `smol: true` sets `JSC::HeapSize` to be `Small` instead of the default `Large`.
|
|
289
|
+
</Accordion>
|
|
290
|
+
|
|
291
|
+
## Environment Data
|
|
292
|
+
|
|
293
|
+
Share data between the main thread and workers using `setEnvironmentData()` and `getEnvironmentData()`.
|
|
294
|
+
|
|
295
|
+
```ts title="index.ts" icon="/icons/typescript.svg"
|
|
296
|
+
import { setEnvironmentData, getEnvironmentData } from "worker_threads";
|
|
297
|
+
|
|
298
|
+
// In main thread
|
|
299
|
+
setEnvironmentData("config", { apiUrl: "https://api.example.com" });
|
|
300
|
+
|
|
301
|
+
// In worker
|
|
302
|
+
const config = getEnvironmentData("config");
|
|
303
|
+
console.log(config); // => { apiUrl: "https://api.example.com" }
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
## Worker Events
|
|
307
|
+
|
|
308
|
+
Listen for worker creation events using `process.emit()`:
|
|
309
|
+
|
|
310
|
+
```ts title="index.ts" icon="/icons/typescript.svg"
|
|
311
|
+
process.on("worker", worker => {
|
|
312
|
+
console.log("New worker created:", worker.threadId);
|
|
313
|
+
});
|
|
314
|
+
```
|
|
315
|
+
|
|
316
|
+
## `Bun.isMainThread`
|
|
317
|
+
|
|
318
|
+
You can check if you're in the main thread by checking `Bun.isMainThread`.
|
|
319
|
+
|
|
320
|
+
```ts
|
|
321
|
+
if (Bun.isMainThread) {
|
|
322
|
+
console.log("I'm the main thread");
|
|
323
|
+
} else {
|
|
324
|
+
console.log("I'm in a worker");
|
|
325
|
+
}
|
|
326
|
+
```
|
|
327
|
+
|
|
328
|
+
This is useful for conditionally running code based on whether you're in the main thread or not.
|