bun
Incredibly fast JavaScript runtime, bundler, test runner, and package manager – all in one
Top Related Projects
A modern runtime for JavaScript and TypeScript.
Node.js JavaScript runtime ✨🐢🚀✨
An extremely fast bundler for the web
Build system optimized for JavaScript and TypeScript, written in Rust
Unified developer tools for JavaScript, TypeScript, and the web
Rust-based platform for the Web
Quick Overview
Bun is an all-in-one JavaScript runtime and toolkit designed to be a drop-in replacement for Node.js. It aims to provide faster performance, better developer experience, and enhanced compatibility with existing JavaScript and TypeScript codebases. Bun includes a bundler, transpiler, task runner, and npm client.
Pros
- Significantly faster performance compared to Node.js due to its use of the JavaScriptCore engine
- Built-in bundler and transpiler, reducing the need for additional tools
- Native TypeScript support without requiring separate compilation steps
- Improved developer experience with features like hot reloading and a unified CLI
Cons
- Relatively new project, which may lead to stability issues or lack of mature ecosystem support
- Not 100% compatible with all Node.js APIs and modules, potentially requiring code adjustments
- Limited community resources and third-party packages compared to Node.js
- Steeper learning curve for developers already familiar with the Node.js ecosystem
Code Examples
- Basic HTTP server:
const server = Bun.serve({
port: 3000,
fetch(req) {
return new Response("Welcome to Bun!");
},
});
console.log(`Listening on http://localhost:${server.port}`);
- Reading a file:
const file = Bun.file("example.txt");
const text = await file.text();
console.log(text);
- Using the built-in SQLite database:
const db = new Bun.SQLite(":memory:");
db.query("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)").run();
db.query("INSERT INTO users (name) VALUES (?)").run("Alice");
const users = db.query("SELECT * FROM users").all();
console.log(users);
Getting Started
- Install Bun:
curl -fsSL https://bun.sh/install | bash
- Create a new project:
bun init my-project
cd my-project
- Run a JavaScript file:
bun run index.js
- Install dependencies:
bun install <package-name>
- Start a development server with hot reloading:
bun --hot index.js
Competitor Comparisons
A modern runtime for JavaScript and TypeScript.
Pros of Deno
- Built-in TypeScript support without additional configuration
- Secure by default with explicit permissions for file, network, and environment access
- Comprehensive standard library with modern APIs
Cons of Deno
- Smaller ecosystem compared to Node.js, with fewer third-party packages
- Limited compatibility with existing Node.js projects and packages
- Steeper learning curve for developers familiar with Node.js
Code Comparison
Deno:
import { serve } from "https://deno.land/std@0.140.0/http/server.ts";
serve((req) => new Response("Hello World"));
Bun:
export default {
port: 3000,
fetch(req) {
return new Response("Hello World");
},
};
Both Deno and Bun aim to improve upon Node.js, offering enhanced performance and developer experience. Deno focuses on security and modern JavaScript features, while Bun prioritizes speed and compatibility with the existing Node.js ecosystem. Deno's approach to modules and security may require more adaptation for developers, whereas Bun aims to be a drop-in replacement for Node.js with minimal changes required.
Node.js JavaScript runtime ✨🐢🚀✨
Pros of Node.js
- Mature ecosystem with extensive libraries and frameworks
- Widespread adoption and community support
- Well-established tooling and debugging capabilities
Cons of Node.js
- Slower startup times and higher memory usage
- Less efficient handling of concurrent tasks
- Lack of built-in TypeScript support
Code Comparison
Node.js:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
});
server.listen(3000);
Bun:
export default {
port: 3000,
fetch(request) {
return new Response("Hello World");
},
};
The Bun example showcases its more concise syntax and built-in HTTP server functionality, while Node.js requires more boilerplate code. Bun's approach aims to simplify common tasks and improve developer productivity.
Node.js remains a solid choice for its maturity and extensive ecosystem, while Bun offers potential performance improvements and a more modern development experience. The choice between the two depends on specific project requirements and developer preferences.
An extremely fast bundler for the web
Pros of esbuild
- Faster build times for JavaScript and TypeScript projects
- Highly optimized for performance, written in Go
- Focused solely on bundling and minification tasks
Cons of esbuild
- Limited to build-time operations, not a full runtime environment
- Narrower feature set compared to Bun's all-in-one approach
- Requires additional tools for tasks like package management
Code Comparison
esbuild:
import * as esbuild from 'esbuild'
await esbuild.build({
entryPoints: ['app.js'],
bundle: true,
outfile: 'out.js',
})
Bun:
import { build } from 'bun';
await build({
entrypoints: ['./app.ts'],
outdir: './out',
});
Both esbuild and Bun offer build functionality, but Bun provides a more comprehensive environment for JavaScript and TypeScript development. While esbuild excels in build performance, Bun aims to be an all-in-one toolkit, including a runtime, package manager, and build tool. esbuild's focused approach may be preferable for projects requiring only bundling and minification, while Bun's broader feature set caters to developers seeking an integrated development experience.
Build system optimized for JavaScript and TypeScript, written in Rust
Pros of Turborepo
- Specialized in monorepo management and build optimization
- Provides advanced caching mechanisms for faster builds
- Integrates well with existing Node.js ecosystems
Cons of Turborepo
- Limited to build and dependency management tasks
- Requires additional setup and configuration for optimal use
- Not a full JavaScript runtime like Bun
Code Comparison
Turborepo (pipeline configuration):
{
"pipeline": {
"build": {
"dependsOn": ["^build"],
"outputs": ["dist/**", ".next/**"]
}
}
}
Bun (script execution):
import { $ } from "bun";
await $`echo "Hello, Bun!"`;
Turborepo focuses on optimizing builds and managing dependencies in monorepos, while Bun aims to be a complete JavaScript runtime and package manager. Turborepo excels in large-scale project organization, whereas Bun offers faster execution and a more streamlined development experience. The code examples highlight their different use cases: Turborepo for build pipeline configuration and Bun for script execution.
Unified developer tools for JavaScript, TypeScript, and the web
Pros of Rome
- Comprehensive toolchain with linting, formatting, and bundling capabilities
- Strong focus on developer experience and ease of use
- Active community and regular updates
Cons of Rome
- Slower performance compared to Bun
- Less mature and stable than Bun
- More limited ecosystem and third-party integrations
Code Comparison
Rome configuration:
{
"linter": {
"enabled": true,
"rules": {
"recommended": true
}
},
"formatter": {
"enabled": true,
"indentStyle": "space",
"indentSize": 2
}
}
Bun configuration:
export default {
entrypoints: ['./index.ts'],
outdir: './dist',
target: 'browser',
minify: true
};
Rome focuses on providing an all-in-one toolchain with built-in linting and formatting capabilities, while Bun emphasizes speed and performance as a JavaScript runtime and bundler. Rome's configuration is more declarative, while Bun's is more programmatic. Both projects aim to improve the JavaScript development experience, but they take different approaches to achieve this goal.
Rust-based platform for the Web
Pros of swc
- Focused solely on JavaScript/TypeScript compilation and bundling
- More mature project with a longer development history
- Extensive plugin ecosystem for customization
Cons of swc
- Limited to JavaScript/TypeScript ecosystem
- Requires separate runtime for execution
- Less integrated development experience
Code Comparison
swc:
const swc = require('@swc/core');
const output = swc.transformSync('const x = 1;', {
jsc: {
parser: {
syntax: 'ecmascript'
},
target: 'es5'
}
});
Bun:
const { transpile } = require('bun');
const output = transpile('const x = 1;', {
loader: 'js',
target: 'browser'
});
Both swc and Bun offer fast JavaScript/TypeScript compilation, but they serve different purposes. swc is a dedicated compiler and bundler, while Bun is a more comprehensive JavaScript runtime and toolkit. swc excels in its focused approach and extensive plugin system, making it highly customizable for specific compilation needs. However, Bun provides a more integrated experience, combining a runtime, package manager, and bundler in one tool. The choice between them depends on whether you need a specialized compiler or a full-featured JavaScript runtime environment.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Bun
Read the docs â
What is Bun?
Bun is an all-in-one toolkit for JavaScript and TypeScript apps. It ships as a single executable called bun
.
At its core is the Bun runtime, a fast JavaScript runtime designed as a drop-in replacement for Node.js. It's written in Zig and powered by JavaScriptCore under the hood, dramatically reducing startup times and memory usage.
bun run index.tsx # TS and JSX supported out-of-the-box
The bun
command-line tool also implements a test runner, script runner, and Node.js-compatible package manager. Instead of 1,000 node_modules for development, you only need bun
. Bun's built-in tools are significantly faster than existing options and usable in existing Node.js projects with little to no changes.
bun test # run tests
bun run start # run the `start` script in `package.json`
bun install <pkg> # install a package
bunx cowsay 'Hello, world!' # execute a package
Install
Bun supports Linux (x64 & arm64), macOS (x64 & Apple Silicon) and Windows (x64).
Linux users â Kernel version 5.6 or higher is strongly recommended, but the minimum is 5.1.
x64 users â if you see "illegal instruction" or similar errors, check our CPU requirements
# with install script (recommended)
curl -fsSL https://bun.sh/install | bash
# on windows
powershell -c "irm bun.sh/install.ps1 | iex"
# with npm
npm install -g bun
# with Homebrew
brew tap oven-sh/bun
brew install bun
# with Docker
docker pull oven/bun
docker run --rm --init --ulimit memlock=-1:-1 oven/bun
Upgrade
To upgrade to the latest version of Bun, run:
bun upgrade
Bun automatically releases a canary build on every commit to main
. To upgrade to the latest canary build, run:
bun upgrade --canary
Quick links
-
Intro
-
Templating
-
CLI
-
Runtime
-
Package manager
-
Bundler
-
Test runner
-
Package runner
-
API
- HTTP server (
Bun.serve
) - WebSockets
- Workers
- Binary data
- Streams
- File I/O (
Bun.file
) - import.meta
- SQLite (
bun:sqlite
) - PostgreSQL (
Bun.sql
) - Redis (
Bun.redis
) - S3 Client (
Bun.s3
) - FileSystemRouter
- TCP sockets
- UDP sockets
- Globals
- $ Shell
- Child processes (spawn)
- Transpiler (
Bun.Transpiler
) - Hashing
- Colors (
Bun.color
) - Console
- FFI (
bun:ffi
) - C Compiler (
bun:ffi
cc) - HTMLRewriter
- Testing (
bun:test
) - Cookies (
Bun.Cookie
) - Utils
- Node-API
- Glob (
Bun.Glob
) - Semver (
Bun.semver
) - DNS
- fetch API extensions
- HTTP server (
Guides
-
Binary
- Convert a Blob to a string
- Convert a Buffer to a blob
- Convert a Blob to a DataView
- Convert a Buffer to a string
- Convert a Blob to a ReadableStream
- Convert a Blob to a Uint8Array
- Convert a DataView to a string
- Convert a Uint8Array to a Blob
- Convert a Blob to an ArrayBuffer
- Convert an ArrayBuffer to a Blob
- Convert a Buffer to a Uint8Array
- Convert a Uint8Array to a Buffer
- Convert a Uint8Array to a string
- Convert a Buffer to an ArrayBuffer
- Convert an ArrayBuffer to a Buffer
- Convert an ArrayBuffer to a string
- Convert a Uint8Array to a DataView
- Convert a Buffer to a ReadableStream
- Convert a Uint8Array to an ArrayBuffer
- Convert an ArrayBuffer to a Uint8Array
- Convert an ArrayBuffer to an array of numbers
- Convert a Uint8Array to a ReadableStream
-
Ecosystem
- Use React and JSX
- Use EdgeDB with Bun
- Use Prisma with Bun
- Add Sentry to a Bun app
- Create a Discord bot
- Run Bun as a daemon with PM2
- Use Drizzle ORM with Bun
- Build an app with Nuxt and Bun
- Build an app with Qwik and Bun
- Build an app with Astro and Bun
- Build an app with Remix and Bun
- Build a frontend using Vite and Bun
- Build an app with Next.js and Bun
- Run Bun as a daemon with systemd
- Deploy a Bun application on Render
- Build an HTTP server using Hono and Bun
- Build an app with SvelteKit and Bun
- Build an app with SolidStart and Bun
- Build an HTTP server using Elysia and Bun
- Build an HTTP server using StricJS and Bun
- Containerize a Bun application with Docker
- Build an HTTP server using Express and Bun
- Use Neon Postgres through Drizzle ORM
- Server-side render (SSR) a React component
- Read and write data to MongoDB using Mongoose and Bun
- Use Neon's Serverless Postgres with Bun
-
HTMLRewriter
-
HTTP
- Hot reload an HTTP server
- Common HTTP server usage
- Write a simple HTTP server
- Configure TLS on an HTTP server
- Send an HTTP request using fetch
- Proxy HTTP requests using fetch()
- Start a cluster of HTTP servers
- Stream a file as an HTTP Response
- fetch with unix domain sockets in Bun
- Upload files via HTTP using FormData
- Streaming HTTP Server with Async Iterators
- Streaming HTTP Server with Node.js Streams
-
Install
- Add a dependency
- Add a Git dependency
- Add a peer dependency
- Add a trusted dependency
- Add a development dependency
- Add a tarball dependency
- Add an optional dependency
- Generate a yarn-compatible lockfile
- Configuring a monorepo using workspaces
- Install a package under a different name
- Install dependencies with Bun in GitHub Actions
- Using bun install with Artifactory
- Configure git to diff Bun's lockb lockfile
- Override the default npm registry for bun install
- Using bun install with an Azure Artifacts npm registry
- Migrate from npm install to bun install
- Configure a private registry for an organization scope with bun install
-
Process
-
Read file
-
Runtime
- Delete files
- Run a Shell Command
- Import a JSON file
- Import a TOML file
- Set a time zone in Bun
- Set environment variables
- Re-map import paths
- Delete directories
- Read environment variables
- Import a HTML file as text
- Install and run Bun in GitHub Actions
- Debugging Bun with the web debugger
- Install TypeScript declarations for Bun
- Debugging Bun with the VS Code extension
- Inspect memory usage using V8 heap snapshots
- Define and replace static globals & constants
- Codesign a single-file JavaScript executable on macOS
-
Streams
- Convert a ReadableStream to JSON
- Convert a ReadableStream to a Blob
- Convert a ReadableStream to a Buffer
- Convert a ReadableStream to a string
- Convert a ReadableStream to a Uint8Array
- Convert a ReadableStream to an array of chunks
- Convert a Node.js Readable to JSON
- Convert a ReadableStream to an ArrayBuffer
- Convert a Node.js Readable to a Blob
- Convert a Node.js Readable to a string
- Convert a Node.js Readable to an Uint8Array
- Convert a Node.js Readable to an ArrayBuffer
-
Test
- Spy on methods in
bun test
- Bail early with the Bun test runner
- Mock functions in
bun test
- Run tests in watch mode with Bun
- Use snapshot testing in
bun test
- Skip tests with the Bun test runner
- Using Testing Library with Bun
- Update snapshots in
bun test
- Run your tests with the Bun test runner
- Set the system time in Bun's test runner
- Set a per-test timeout with the Bun test runner
- Migrate from Jest to Bun's test runner
- Write browser DOM tests with Bun and happy-dom
- Mark a test as a "todo" with the Bun test runner
- Re-run tests multiple times with the Bun test runner
- Generate code coverage reports with the Bun test runner
- import, require, and test Svelte components with bun test
- Set a code coverage threshold with the Bun test runner
- Spy on methods in
-
Util
- Generate a UUID
- Hash a password
- Escape an HTML string
- Get the current Bun version
- Encode and decode base64 strings
- Compress and decompress data with gzip
- Sleep for a fixed number of milliseconds
- Detect when code is executed with Bun
- Check if two objects are deeply equal
- Compress and decompress data with DEFLATE
- Get the absolute path to the current entrypoint
- Get the directory of the current file
- Check if the current file is the entrypoint
- Get the file name of the current file
- Convert a file URL to an absolute path
- Convert an absolute path to a file URL
- Get the absolute path of the current file
- Get the path to an executable bin file
-
WebSocket
-
Write file
Contributing
Refer to the Project > Contributing guide to start contributing to Bun.
License
Refer to the Project > License page for information about Bun's licensing.
Top Related Projects
A modern runtime for JavaScript and TypeScript.
Node.js JavaScript runtime ✨🐢🚀✨
An extremely fast bundler for the web
Build system optimized for JavaScript and TypeScript, written in Rust
Unified developer tools for JavaScript, TypeScript, and the web
Rust-based platform for the Web
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot