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/overview

152 notes in this subject, read out of this brain and free to use. This is page 1 of 3.

Bun philosophy on Web API standards

Bun strives to implement standard Web APIs wherever possible. Bun introduces new APIs primarily for server-side tasks where no standard exists, such as file I/O and starting an HTTP server. When introducing new APIs, Bun builds on top of standard APIs like Blob, URL, and Request.

bunfig.toml telemetry setting

The telemetry field enables or disables analytics. Default is true. This is equivalent to the DO_NOT_TRACK environment variable. Currently only controls anonymous crash reports; future plans include collecting API usage and build times.

bunfig.toml loader field for file extensions

The loader field maps file extensions to loaders to load file types Bun doesn't support natively. Example: [loader] ".bagel" = "tsx". Supported loaders are: jsx, js, ts, tsx, css, file, json, toml, wasm, napi, base64, dataurl, text.

bunfig.toml preload scripts

The preload field is an array of scripts or plugins to execute before running a file or script. Example: preload = ["./preload.ts"]. This registers plugins by adding them to the list.

bunfig.toml logLevel

Set the logLevel field to one of: "debug", "warn", or "error" to control logging verbosity.

bunfig.toml env setting for .env loading

The env field controls automatic .env file loading. By default, Bun loads .env files. Set env = false to disable this. Can also use object syntax: [env] file = false. Files passed explicitly with --env-file are still loaded even when default loading is disabled.

bunfig.toml define field for constant replacement

The define field replaces global identifiers with constant expressions wherever they appear. Expressions should be JSON strings. Example: [define] "process.env.bagel" = "'lox'". Values are parsed as JSON; single-quoted strings are supported and 'undefined' becomes undefined in JS.

bunfig.toml JSX configuration

JSX can be configured in bunfig.toml using fields: jsx, jsxFactory, jsxFragment, and jsxImportSource. These correspond to TypeScript's tsconfig.json compilerOptions and support non-TypeScript projects. Example: jsx = "react", jsxFactory = "h", jsxFragment = "Fragment", jsxImportSource = "react".

bunfig.toml smol mode

The smol field enables smol mode when set to true, which reduces memory usage at the cost of performance.

bunfig.toml configuration file location

bunfig.toml is Bun's configuration file placed in the project root alongside package.json. For global configuration, create a .bunfig.toml file at $HOME/.bunfig.toml or $XDG_CONFIG_HOME/.bunfig.toml. If both global and local bunfig files exist, they are shallow-merged with local overriding global. CLI flags override bunfig settings where applicable.

bunfig.toml console.depth setting

The [console] section has a depth field that sets the default depth for console.log() object inspection. Default is 2. Higher values show more nested properties but may produce verbose output. The --console-depth CLI flag overrides this.

DO_NOT_TRACK environment variable

DO_NOT_TRACK=1 disables uploading crash reports to bun.report on crash and disables telemetry. On macOS and Windows, crash report uploads are enabled by default. Other telemetry is not sent by default.

--env-file flag for custom .env files

The --env-file flag overrides which .env files Bun loads. It works with both running files and package.json scripts. Multiple --env-file flags can be used: bun --env-file=.env.1 src/index.ts or bun --env-file=.env.abc --env-file=.env.def run build.

--no-env-file flag disables automatic .env loading

Use --no-env-file to disable Bun's automatic .env file loading: bun run --no-env-file index.ts. This is useful in production or CI/CD pipelines where you want to rely solely on system environment variables. Files passed with --env-file still load even when default loading is disabled.

.env files automatically loaded by Bun

Bun automatically reads the following .env files in order of increasing precedence: .env, .env.production/.env.development/.env.test (depending on NODE_ENV value), and .env.local.

Set environment variables on command line

Environment variables can be set on the command line before running a Bun command. On Linux/macOS use: FOO=helloworld bun run dev. On Windows CMD use: set FOO=helloworld && bun run dev. On Windows PowerShell use: $env:FOO="helloworld"; bun run dev.

BUN_RUNTIME_TRANSPILER_CACHE_PATH environment variable

The runtime transpiler caches transpiled output of source files larger than 4 KB to make CLIs load faster. BUN_RUNTIME_TRANSPILER_CACHE_PATH sets the cache directory. If set to empty string or "0", caching is disabled. If unset, cache is written to the platform-specific cache directory. Cached files use the .pile extension and cache includes both transpiled output and sourcemaps.

NO_COLOR and FORCE_COLOR environment variables

NO_COLOR=1 disables ANSI color output. FORCE_COLOR=1 forces ANSI color output on, even if NO_COLOR is set.

TypeScript environment variable typing

In TypeScript, all properties of process.env are typed as string | undefined. To get autocompletion and treat a variable as non-optional string, use interface merging: declare module "bun" { interface Env { AWESOME: string; } }. This adds the AWESOME property to process.env and Bun.env globally.

Read environment variables via process.env, Bun.env, or import.meta.env

Read environment variables using process.env.API_TOKEN, Bun.env.API_TOKEN, or import.meta.env.API_TOKEN. All three are aliases of each other. Print all environment variables with: bun --print process.env.

NODE_TLS_REJECT_UNAUTHORIZED environment variable

NODE_TLS_REJECT_UNAUTHORIZED=0 disables SSL certificate validation. This is useful for testing and debugging, but should be used very cautiously in production. This variable was introduced by Node.js and Bun maintains it for compatibility.

Set environment variables programmatically

Assign a property to process.env to set environment variables programmatically in code: process.env.FOO = "hello";

.env variable expansion

Bun automatically expands environment variables, allowing you to reference previously-defined variables: FOO=world and BAR=hello$FOO results in process.env.BAR being "helloworld". To disable expansion, escape the $ with a backslash: BAR=hello\$FOO results in process.env.BAR being "hello$FOO".

.env file quotation marks supported

Bun supports double quotes, single quotes, and template literal backticks in .env files: FOO='hello', FOO="hello", or FOO=`hello`.

BUN_CONFIG_NO_CLEAR_TERMINAL_ON_RELOAD environment variable

BUN_CONFIG_NO_CLEAR_TERMINAL_ON_RELOAD=true prevents bun --watch from clearing the console on reload.

BUN_CONFIG_VERBOSE_FETCH environment variable

BUN_CONFIG_VERBOSE_FETCH=curl logs fetch request URLs, methods, request headers, and response headers to the console. This also works with node:http. BUN_CONFIG_VERBOSE_FETCH=1 is equivalent to curl output except without the curl formatting.

TMPDIR environment variable for Bun

Bun uses a temporary directory to store intermediate assets during bundling or other operations. If TMPDIR is unset, defaults to: /tmp on Linux, /private/tmp on macOS.

BUN_OPTIONS environment variable prepends arguments

BUN_OPTIONS prepends command-line arguments to any Bun execution. For example, BUN_OPTIONS="--hot" makes bun run dev behave like bun --hot run dev.

Runtime transpiler cache properties

The runtime transpiler cache is global and shared across all projects. It is content-addressable, so it never contains duplicate entries. It is safe to delete at any time, even while a Bun process is running. Disable this cache when using ephemeral filesystems like Docker. Bun's Docker images disable it automatically.

Disable runtime transpiler cache

To disable the runtime transpiler cache, set BUN_RUNTIME_TRANSPILER_CACHE_PATH to an empty string or the string "0": BUN_RUNTIME_TRANSPILER_CACHE_PATH=0 bun run dev.

Auto .env loading disabled when Bun invoked as node

When Bun is invoked as node (via bun --bun, bunx --bun, or a node symlink pointing at Bun), automatic .env loading is disabled to match Node.js behavior. This allows tools like Vite to pick the correct .env.{mode} file. Explicit --env-file arguments are still honored.

Disable .env loading in bunfig.toml

Set env = false in bunfig.toml to disable loading .env files: [env] setting with value false disables the default .env loading behavior.

globalThis aliases to global

globalThis is a cross-platform global that aliases to the Node.js global object in Bun.

ResolveMessage global

ResolveMessage is a Bun-specific global object.

BuildMessage global

BuildMessage is a Bun-specific global object.

Bun global object

Bun is a Bun-specific global object that is subject to change as additional APIs are added.

prompt() global function

prompt is a Web API global available in Bun, intended for command-line tools.

HTMLRewriter global

HTMLRewriter is a Cloudflare global API available in Bun.

confirm() global function

confirm is a Web API global available in Bun, intended for command-line tools.

alert() global function

alert is a Web API global available in Bun, intended for command-line tools.

Bun global objects and APIs

Bun implements the following global objects across Web, Node.js, Cloudflare, and Bun-specific APIs: AbortController, AbortSignal, alert, Blob, Buffer, Bun, ByteLengthQueuingStrategy, confirm, __dirname, __filename, atob(), btoa(), BuildMessage, clearImmediate(), clearInterval(), clearTimeout(), console, CountQueuingStrategy, Crypto, crypto, CryptoKey, CustomEvent, Event (also ErrorEvent, CloseEvent, MessageEvent), EventTarget, exports, fetch, FormData, global, globalThis (aliases to global), Headers, HTMLRewriter, JSON, MessageEvent, module, performance, process, prompt, queueMicrotask(), ReadableByteStreamController, ReadableStream, ReadableStreamDefaultController, ReadableStreamDefaultReader, reportError, require(), ResolveMessage, Response, Request, setImmediate(), setInterval(), setTimeout(), ShadowRealm (Stage 3 proposal), SubtleCrypto, DOMException, TextDecoder, TextEncoder, TransformStream, TransformStreamDefaultController, URL, URLSearchParams, WebAssembly, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter.

bun command resolution order

Absolute paths and paths starting with './' or '.\\' are always executed as source files. Unless you use 'bun run', a name with an allowed extension resolves to the file rather than a package.json script. When a package.json script and a file have the same name, 'bun run' prefers the script. The full resolution order is: 1) package.json scripts ('bun run build'), 2) Source files ('bun run src/main.js'), 3) Binaries from project packages ('bun add eslint && bun run eslint'), 4) System commands ('bun run ls', 'bun run' only).

bun run --smol flag for memory-constrained environments

In memory-constrained environments, use 'bun --smol run index.tsx' to reduce memory usage at a cost to performance. The --smol flag makes the garbage collector run more frequently, which can slow down execution. Bun adjusts the garbage collector's heap size based on available memory (accounting for cgroups and other memory limits) with and without the --smol flag.

bun run --console-depth flag

Use 'bun --console-depth <number> run index.tsx' to control the depth of object inspection in console output. The flag sets how deeply nested objects are displayed in console.log() output. The default depth is 2. Higher values show more nested properties but may produce verbose output for complex objects.

bun run - pipes code from stdin

'bun run -' reads JavaScript, TypeScript, TSX, or JSX from stdin and executes it without writing to a temporary file first. Example: 'echo "console.log('Hello')" | bun run -' outputs 'Hello'. You can also redirect files: 'bun run - < secretly-typescript.js'. 'bun run -' treats all input as TypeScript with JSX support.

bun run --filter for monorepos

In a monorepo, use 'bun run --filter <name_pattern> <script>' to execute a script in every package whose name matches the pattern. For example, 'bun run --filter 'ba*' <script>' executes the script in packages named 'bar' and 'baz' but not 'foo'.

bun run --bun flag overrides shebang

When a package.json script references a locally-installed CLI (like vite or next) that is a JavaScript file with a shebang (#!/usr/bin/env node), Bun respects the shebang by default and executes it with node. Use the --bun flag to override this: 'bun run --bun vite' executes the CLI with Bun instead of Node.js.

bun run respects package.json lifecycle hooks

Bun respects lifecycle hooks in package.json. For instance, 'bun run clean' runs 'preclean' and 'postclean' if defined. If the 'pre<script>' fails, Bun does not run the script itself.

bun run without arguments lists available scripts

Running 'bun run' without any arguments displays a list of all available scripts defined in package.json with their commands.

bun run package.json scripts

Use 'bun run <script>' to execute named scripts defined in package.json 'scripts' field. The command syntax is 'bun [bun flags] run <script> [script flags]'. Bun executes the script command in a subshell. On Linux and macOS, it checks for bash, sh, and zsh in that order, using the first one found. On Windows, it uses the Bun Shell to support bash-like syntax and common commands. Startup time for 'bun run' is approximately 6ms compared to roughly 170ms for 'npm run' on Linux.

bun --watch flag for watch mode

To run a file in watch mode, use the --watch flag: 'bun --watch run index.tsx'. When using 'bun run', put Bun flags like --watch immediately after 'bun', not at the end. 'bun --watch run dev' is correct; 'bun run dev --watch' is incorrect because flags at the end are passed through to the script itself.

bun run can be shortened to naked command

You can omit the 'run' keyword and use a naked command like 'bun index.tsx' or 'bun index.js', which behaves identically to 'bun run index.tsx' or 'bun run index.js'.

bun run executes source files

Use 'bun run' to execute a source file. Bun supports TypeScript and JSX with no configuration. Bun transpiles every file on the fly with its native transpiler before running it. Supported file extensions are .js, .jsx, .ts, and .tsx.

Bun startup time benchmark

On Linux running a Hello World script, bun hello.js takes 5.2ms while node hello.js takes 25.1ms.

Bun runtime uses JavaScriptCore engine

Bun uses the JavaScriptCore engine developed by Apple for Safari. It usually starts and runs faster than V8, the engine used by Node.js and Chromium-based browsers. Bun's transpiler and runtime are written in Rust. On Linux, Bun starts 4x faster than Node.js.

REPL syntax highlighting

The REPL provides syntax highlighting as you type.

REPL keybindings Ctrl+C

Pressing `Ctrl+C` cancels the current input in the REPL. Press it twice on an empty line to exit the REPL.

REPL keybindings Ctrl+T

Pressing `Ctrl+T` swaps the two characters before the cursor in the REPL.

REPL keybindings Tab

Pressing `Tab` triggers auto-complete in the REPL.

REPL keybindings Ctrl+L

Pressing `Ctrl+L` clears the screen in the REPL.

Give your agent this brain