Bun APIs overview table
Bun provides APIs on the Bun global object and through built-in modules. The following APIs are available: HTTP Server (Bun.serve), Shell ($), Bundler (Bun.build), File I/O (Bun.file, Bun.write, Bun.stdin, Bun.stdout, Bun.stderr), Child Processes (Bun.spawn, Bun.spawnSync), TCP Sockets (Bun.listen, Bun.connect), UDP Sockets (Bun.udpSocket), WebSockets (new WebSocket() for client, Bun.serve for server), Transpiler (Bun.Transpiler), Routing (Bun.FileSystemRouter), Streaming HTML (HTMLRewriter), Headless Browser (Bun.WebView), Hashing (Bun.password, Bun.hash, Bun.CryptoHasher, Bun.sha), CSRF Protection (Bun.CSRF.generate, Bun.CSRF.verify), SQLite (bun:sqlite), SQL Client (Bun.SQL, Bun.sql), Redis/Valkey Client (Bun.RedisClient, Bun.redis), FFI (bun:ffi), DNS (Bun.dns.lookup, Bun.dns.prefetch, Bun.dns.getCacheStats), Testing (bun:test), Workers (new Worker()), Module Loaders (Bun.plugin), Glob (Bun.Glob), Cookies (Bun.Cookie, Bun.CookieMap), Node-API, import.meta, Utilities (Bun.version, Bun.revision, Bun.env, Bun.main), Sleep & Timing (Bun.sleep, Bun.sleepSync, Bun.nanoseconds), Random & UUID (Bun.randomUUIDv7), System & Environment (Bun.which), Comparison & Inspection (Bun.peek, Bun.deepEquals, Bun.deepMatch, Bun.inspect), String & Text Processing (Bun.escapeHTML, Bun.stringWidth, Bun.indexOfLine), URL & Path Utilities (Bun.fileURLToPath, Bun.pathToFileURL), Compression (Bun.gzipSync, Bun.gunzipSync, Bun.deflateSync, Bun.inflateSync, Bun.zstdCompressSync, Bun.zstdDecompressSync, Bun.zstdCompress, Bun.zstdDecompress), Stream Processing (Bun.readableStreamTo* family of functions), Memory & Buffer Management (Bun.ArrayBufferSink, Bun.allocUnsafe, Bun.concatArrayBuffers), Module Resolution (Bun.resolveSync), Parsing & Formatting (Bun.semver, Bun.TOML.parse, Bun.XML, Bun.markdown, Bun.color, Bun.Image), and Low-level/Internals (Bun.mmap, Bun.gc, Bun.generateHeapSnapshot, bun:jsc).
Bun design philosophy on standard APIs
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. In these cases, Bun's approach still builds atop standard APIs like Blob, URL, and Request.
Archive files() return value details
archive.files() returns a Promise<Map<string, File>>. Each File object includes: name property (file path within archive using forward slash separators), size property (file size in bytes), lastModified property (modification timestamp), and standard Blob methods like text(), arrayBuffer(), and stream().
Creating Bun.Archive example
Example of creating an uncompressed tar archive: const archive = new Bun.Archive({ 'README.md': '# My Project', 'src/index.ts': "console.log('Hello');", 'package.json': JSON.stringify({ name: 'my-project' }) });
Bun.Archive - tar archive creation and extraction
Bun.Archive is Bun's native API for tar archives. It creates archives from in-memory data, extracts archives to disk, and reads archive contents without extraction. Archives are uncompressed by default.
Archive.files() method
The files() method returns archive contents as a Map of File objects without extracting to disk. Accepts optional glob parameter for filtering (string or readonly string[]). Returns only regular files, no directories. Returns Promise<Map<string, File>>. File objects include properties: name (file path with forward slashes), size (bytes), lastModified (timestamp), and standard Blob methods like text(), arrayBuffer(), and stream(). Loads file contents into memory.
Archive bytes and blob retrieval example
Example of getting archive data: const archive = new Bun.Archive({ 'hello.txt': 'Hello, World!' }); const bytes = await archive.bytes(); const blob = await archive.blob(); For gzipped: const gzipped = new Bun.Archive({ 'hello.txt': 'Hello, World!' }, { compress: 'gzip' }); const gzippedBytes = await gzipped.bytes(); const gzippedBlob = await gzipped.blob();
Archive path validation and security
Bun.Archive validates paths during extraction and rejects absolute paths (POSIX / prefix, Windows drive letters like C:\ or C:/, and UNC paths like \\server\share) and unsafe symlink targets. It normalizes away path traversal components (..) to prevent directory escape attacks, so dir/sub/../file becomes dir/file.
Archive.extract() glob filtering example
Use glob patterns with extract() to filter files: archive.extract('./extracted', { glob: '**/*.ts' }) extracts only TypeScript files. Can pass array of patterns: { glob: ['src/**', 'lib/**'] }. Negative patterns work: { glob: ['**', '!node_modules/**'] } extracts everything except node_modules. When mixing positive and negative patterns, entries must match at least one positive pattern and no negative pattern.
Archive compression options
Archive constructor accepts an options parameter with compress and level properties. compress can be 'gzip' to enable gzip compression. level is a number from 1-12 for custom compression level (default 6 when gzip is enabled, where 1 is fastest and 12 is smallest).
Creating Bun.Archive from files object
Use new Bun.Archive() to create an archive from an object where keys are file paths and values are file contents. File contents can be strings, Blobs, ArrayBufferViews (like Uint8Array), or ArrayBuffers.
Creating Archive from existing tar data
Create an archive from existing tar or tar.gz data by passing the compressed/uncompressed bytes or Blob to new Bun.Archive(). Compression (gzip) is automatically detected.
Archive security with untrusted data example
Example of validating archive paths before extraction: const archive = new Bun.Archive(untrustedData); const files = await archive.files(); for (const [path] of files) { if (path.startsWith('.') || path.includes('/.')) { throw new Error(`Hidden file rejected: ${path}`); } if (!path.startsWith('src/') && !path.startsWith('lib/')) { throw new Error(`Unexpected path: ${path}`); } } await archive.extract('./safe-output');
Archive glob pattern filtering
Bun.Archive supports glob patterns for filtering files during extraction and reading. Patterns match against archive entry paths normalized to use forward slashes. Positive patterns specify what to include, negative patterns prefixed with '!' specify what to exclude. When only negative patterns are passed, Bun includes all entries not matching them. Supported patterns: * (match any except /), ** (match any including /), ? (single character), [abc] (character set), {a,b} (alternatives), !pattern (negation).
Archive write to disk with compression example
Example of writing archive to disk: const archive = new Bun.Archive({ 'file1.txt': 'content1', 'file2.txt': 'content2' }); await Bun.write('output.tar', archive); For gzipped: const compressed = new Bun.Archive({ 'src/index.ts': "console.log('Hello');" }, { compress: 'gzip' }); await Bun.write('output.tar.gz', compressed);
Archive read contents without extracting example
Example of reading archive contents without extracting: const tarball = await Bun.file('package.tar.gz').bytes(); const archive = new Bun.Archive(tarball); const files = await archive.files(); for (const [path, file] of files) { console.log(`${path}: ${await file.text()}`); }
Archive extract from fetch example
Example of extracting an archive from a fetch response: const response = await fetch('https://example.com/archive.tar.gz'); const archiveFromFetch = new Bun.Archive(await response.blob());
Archive extract from file example
Example of extracting an archive from file: const tarball = await Bun.file('package.tar.gz').bytes(); const archive = new Bun.Archive(tarball); const entryCount = await archive.extract('./output'); console.log(`Extracted ${entryCount} entries`);
Archive.bytes() method
The bytes() method returns the archive as a Uint8Array. Uses the compression setting from the constructor (gzipped if { compress: 'gzip' } was passed). Returns a Promise<Uint8Array<ArrayBuffer>>.
Archive.extract() method
The extract() method writes all files from an archive to a directory. Accepts path parameter for target directory and optional options parameter with glob property for filtering. Returns a Promise that resolves to the number of entries extracted (files, directories, and symlinks). Creates the target directory if it doesn't exist and overwrites existing files. On Windows, symlinks are always skipped during extraction; on Linux and macOS, symlinks are extracted normally.
Archive with various file content types example
Example of creating archive with different content types: const data = 'binary data'; const arrayBuffer = new ArrayBuffer(8); const archive = new Bun.Archive({ 'text.txt': 'Plain text', 'blob.bin': new Blob([data]), 'bytes.bin': new Uint8Array([1, 2, 3, 4]), 'buffer.bin': arrayBuffer });
Archive.files() glob filtering example
Use glob patterns with files() to filter which files are returned: archive.files('**/*.ts') gets only TypeScript files, archive.files('src/*') gets files in src directory, archive.files('**/*.json') gets all JSON files recursively. Can pass array: archive.files(['**/*.ts', '**/*.js']) gets multiple file types. Returns empty Map if no files match.
Archive.blob() method
The blob() method returns the archive as a Blob. Uses the compression setting from the constructor (gzipped if { compress: 'gzip' } was passed). Returns a Promise<Blob>.
Archive constructor type signature
Archive constructor signature: constructor(data: ArchiveInput, options?: ArchiveOptions). ArchiveInput is Record<string, string | Blob | Bun.ArrayBufferView | ArrayBufferLike> | Blob | Bun.ArrayBufferView | ArrayBufferLike. ArchiveOptions is { compress?: 'gzip', level?: number }.
Archive error handling
Archive operations can fail due to corrupted data, I/O errors, or invalid paths. Common error scenarios: corrupted/truncated archives may defer errors until read/extract operations, permission denied (code 'EACCES') when target directory is not writable, disk full (code 'ENOSPC') when insufficient space, and invalid paths for malformed file paths. Use try/catch blocks to handle errors.
bunfig.toml install.globalStore configuration
Set [install] globalStore = true to share package installations across projects in a global virtual store at <cache>/links/ when using the "isolated" linker. Bun links node_modules/.bun/<pkg>@<ver> into the store instead of materializing packages. Makes warm installs after rm -rf node_modules faster. Default false. Can also set with BUN_INSTALL_GLOBAL_STORE environment variable.
bunfig.toml install.lockfile configuration
Configure lockfile generation in [install.lockfile] section: save = true (default, generate lockfile on bun install), print = "yarn" (generate non-Bun lockfile alongside bun.lock, yarn is the only supported value, Bun always creates bun.lock).
bunfig.toml install.cache configuration
Configure cache behavior in [install.cache] section: dir = "~/.bun/install/cache" (cache directory), disable = false (when true, don't load from global cache, may still write to node_modules/.cache), disableManifest = false (when true, always resolve latest versions from registry).
bunfig.toml install.ca and install.cafile configuration
Configure CA certificates in [install] section. Set ca to the certificate string, or cafile to the path of a certificate file. The file can contain multiple certificates. Example: ca = "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----" or cafile = "path/to/cafile"
bunfig.toml file location and scope
Place bunfig.toml in your project root alongside package.json for local configuration. For global configuration of the package manager, create .bunfig.toml at $HOME/.bunfig.toml or $XDG_CONFIG_HOME/.bunfig.toml. Only package manager commands (bun install, bun add, bun remove, bun update, bun pm, bunx) read the global file. If both global and local bunfig files exist, both are loaded and keys in the local file override the global file. CLI flags override bunfig settings where applicable.
bunfig.toml install.linkWorkspacePackages configuration
Set [install] linkWorkspacePackages = true (default) or false to control whether to link workspace packages from the monorepo root to their respective node_modules directories.
bunfig.toml install.registry configuration
Configure npm registry in [install] registry section. Options: registry = "https://registry.npmjs.org" (string), registry = { url = "https://registry.npmjs.org", token = "123456" } (with token), registry = "https://username:password@registry.npmjs.org" (with credentials). Default is https://registry.npmjs.org/.
bunfig.toml install.logLevel configuration
Set [install] logLevel to one of "debug", "warn", or "error" to configure log level for bun install.
bunfig.toml install.dryRun configuration
Set [install] dryRun = true to resolve dependencies without installing them. Default is false. When true, equivalent to passing --dry-run to all bun install commands.
bunfig.toml install.frozenLockfile configuration
Set [install] frozenLockfile = true to prevent bun install from updating bun.lock. Default is false. If package.json and existing bun.lock disagree, the install errors.
bunfig.toml install.security.scanner configuration
Configure a security scanner in [install.security] scanner field to scan packages for vulnerabilities before installation. Example: [install.security] scanner = "@oven/bun-security-scanner". When configured: auto-install is disabled, packages are scanned before installation, installation is cancelled if fatal issues found, security warnings display during installation.
bunfig.toml install.minimumReleaseAge configuration
Set [install] minimumReleaseAge to a number (in seconds) for minimum age of npm package versions. Default null (disabled). Bun filters out versions published more recently than this threshold. Example: minimumReleaseAge = 259200 (3 days)
bunfig.toml install.auto configuration
Configure auto-install behavior with [install] auto. Valid values: "auto" (default, resolve from node_modules or auto-install), "force" (always auto-install even if node_modules exists), "disable" (never auto-install), "fallback" (check node_modules first, then auto-install any not found, enabled with bun -i).
bunfig.toml install.saveTextLockfile configuration
Set [install] saveTextLockfile = true (default since Bun v1.2) to generate a text-based bun.lock file. Set to false to generate a binary bun.lockb instead when no lockfile is present.
bunfig.toml install.concurrentScripts configuration
Set [install] concurrentScripts to the maximum number of concurrent lifecycle scripts to run at once. Defaults to two times the number of CPU cores. Equivalent to the --concurrent-scripts flag.
bunfig.toml install.ignoreScripts configuration
Set [install] ignoreScripts = true to skip lifecycle scripts during install. Default is false. Equivalent to the --ignore-scripts flag. When true, Bun does not run preinstall, install, postinstall, or prepare scripts for your project or packages in trustedDependencies.
bunfig.toml install.exact configuration
Set [install] exact = true to set exact versions in package.json instead of caret ranges. Default is false. By default Bun uses caret ranges like ^2.4.1 which accepts any version from 2.4.1 up to (but not including) 3.0.0.
bunfig.toml install.production configuration
Set [install] production = true to enable production mode. In production mode, Bun does not install devDependencies and freezes the lockfile (same as install.frozenLockfile). Default is false. Use --production CLI flag for a single install. Since production mode freezes the lockfile, bun add, bun remove, and bun update fail while it is set.
bunfig.toml install.peer configuration
Set [install] peer = true (default) or false to control whether to install peer dependencies.
bunfig.toml install.hoistPattern configuration
Set [install] hoistPattern to glob patterns of packages to hoist to fallback directory in virtual store when using "isolated" linker. Default hoists every package (equivalent to ["*"]). Example: hoistPattern = ["*"]. Similar to pnpm's hoist-pattern.
bunfig.toml install.prefer configuration
Configure package resolution with [install] prefer. Valid values: "online" (default, check registry for stale packages as needed), "offline" (skip staleness checks, resolve from local cache, equivalent to --prefer-offline), "latest" (always check npm for latest matching versions, equivalent to --prefer-latest).
bunfig.toml install.dev configuration
Set [install] dev = true (default) or false to control whether to install development dependencies.
bunfig.toml install.optional configuration
Set [install] optional = true (default) or false to control whether to install optional dependencies.
bunfig.toml console.depth configuration
Set [console] depth to configure 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 setting.
bunfig.toml install.globalBinDir configuration
Set [install] globalBinDir to the directory where Bun links binaries of globally installed packages. Environment variable: BUN_INSTALL_BIN. Example: globalBinDir = "~/.bun/bin"
bunfig.toml .env file loading configuration
Bun loads .env files by default. To disable automatic .env loading, set env = false or use [env] section with file = false. Bun still loads files explicitly passed with --env-file even when default loading is disabled. Use in production or CI/CD to rely solely on system environment variables.
bunfig.toml telemetry configuration
Set telemetry = false to disable telemetry. This controls anonymous crash reports and is equivalent to the DO_NOT_TRACK environment variable. By default, telemetry is enabled.
bunfig.toml preload configuration
The preload field accepts an array of scripts or plugins to execute before running a file or script. Example: preload = ["./preload.ts"]. This allows registering plugins before bun run-ing a file.
bunfig.toml install.scopes configuration
Configure registries for particular scopes in [install.scopes] section. Example: myorg = "https://username:password@registry.myorg.com/" (string), myorg = { username = "myusername", password = "$npm_password", url = "https://registry.myorg.com/" } (with credentials, supports $variable references), myorg = { token = "$npm_token", url = "https://registry.myorg.com/" } (with token).
bunfig.toml smol mode configuration
Set smol = true to enable smol mode, which reduces memory usage at the cost of performance. Can be set as a top-level runtime setting or under [test] section for test-specific configuration.
bunfig.toml install.publicHoistPattern configuration
Set [install] publicHoistPattern to glob patterns of packages to hoist to root node_modules when using "isolated" linker. Default []. Example: publicHoistPattern = ["*eslint*", "*prettier*"]. Similar to pnpm's public-hoist-pattern.
bunfig.toml install.hoist configuration
Set [install] hoist = true (default) or false to control creation of node_modules/.bun/node_modules fallback directory when using "isolated" linker. When false, skips creating this directory. Undeclared imports then fail unless package is linked at project root node_modules. Default true. Similar to pnpm's hoist setting; takes precedence over install.hoistPattern. Only applies to "isolated" linker.
bunfig.toml install.linker configuration
Configure linker strategy for node_modules layout with [install] linker. Valid values: "hoisted" (link dependencies in shared node_modules), "isolated" (link dependencies inside each package installation). Defaults to "isolated" for new workspaces, "hoisted" for new single-package projects and existing projects.
bunfig.toml install.minimumReleaseAgeExcludes configuration
Set [install] minimumReleaseAgeExcludes to an array of package names exempt from minimumReleaseAge check. Default []. Example: minimumReleaseAgeExcludes = ["@types/bun", "typescript"]
bunfig.toml run.shell configuration
Configure shell used by bun run with [run] shell. Valid values: "system" (default outside Windows, uses system shell), "bun" (default on Windows, uses Bun's shell). Example: [run] shell = "system" to always use system shell.