Bun is a free and open-source all-in-one JavaScript runtime and toolkit built for speed. Written in Zig and powered by JavaScriptCore, it serves as a FOSS alternative to Node.js and npm/yarn/pnpm, offering dramatically faster startup times, built-in TypeScript support, JSX transpilation, and a comprehensive toolkit including bundler, test runner, and package manager in a single binary.
1. Prerequisites
Hardware Requirements
Software Requirements
Network Requirements
2. Supported Operating Systems
Bun officially supports:
3. Installation
Method 1: Official Installer (Recommended)
#### Linux/macOS/WSL
# Install Bun using official script
curl -fsSL https://bun.sh/install | bash
# Add to PATH (add to ~/.bashrc or ~/.zshrc)
export BUN_INSTALL="$HOME/.bun"
export PATH="$BUN_INSTALL/bin:$PATH"
# Reload shell configuration
source ~/.bashrc # or ~/.zshrc
# Verify installation
bun --version
#### Windows (Native - Experimental)
# Install using PowerShell (experimental)
powershell -c "irm bun.sh/install.ps1 | iex"
# Or use WSL2 (recommended)
wsl curl -fsSL https://bun.sh/install | bash
Method 2: Package Managers
#### RHEL/CentOS/Rocky Linux/AlmaLinux
# Download latest binary
BUN_VERSION=$(curl -s https://api.github.com/repos/oven-sh/bun/releases/latest | grep tag_name | cut -d '"' -f 4)
curl -LO "https://github.com/oven-sh/bun/releases/download/${BUN_VERSION}/bun-linux-x64.zip"
# Extract and install
unzip bun-linux-x64.zip
sudo mv bun-linux-x64/bun /usr/local/bin/
sudo chmod +x /usr/local/bin/bun
# Create symlinks
sudo ln -s /usr/local/bin/bun /usr/local/bin/bunx
# Verify installation
bun --version
#### Debian/Ubuntu
# Method 1: Official script (recommended)
curl -fsSL https://bun.sh/install | bash
# Method 2: Manual binary installation
BUN_VERSION=$(curl -s https://api.github.com/repos/oven-sh/bun/releases/latest | grep tag_name | cut -d '"' -f 4)
wget "https://github.com/oven-sh/bun/releases/download/${BUN_VERSION}/bun-linux-x64.zip"
unzip bun-linux-x64.zip
sudo mv bun-linux-x64/bun /usr/local/bin/
sudo chmod +x /usr/local/bin/bun
# Add to PATH
echo 'export PATH="/usr/local/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc
#### Arch Linux
# Install from AUR
yay -S bun-bin
# Or using paru
paru -S bun-bin
# Verify installation
bun --version
#### Alpine Linux
# Install dependencies
apk add --no-cache curl unzip
# Download Bun for musl
BUN_VERSION=$(curl -s https://api.github.com/repos/oven-sh/bun/releases/latest | grep tag_name | cut -d '"' -f 4)
curl -LO "https://github.com/oven-sh/bun/releases/download/${BUN_VERSION}/bun-linux-x64-musl.zip"
# Extract and install
unzip bun-linux-x64-musl.zip
mv bun-linux-x64-musl/bun /usr/local/bin/
chmod +x /usr/local/bin/bun
# Create bunx symlink
ln -s /usr/local/bin/bun /usr/local/bin/bunx
#### openSUSE
# Install via zypper (if available in future)
# Currently use manual installation
BUN_VERSION=$(curl -s https://api.github.com/repos/oven-sh/bun/releases/latest | grep tag_name | cut -d '"' -f 4)
wget "https://github.com/oven-sh/bun/releases/download/${BUN_VERSION}/bun-linux-x64.zip"
unzip bun-linux-x64.zip
sudo mv bun-linux-x64/bun /usr/local/bin/
sudo chmod +x /usr/local/bin/bun
#### macOS
# Method 1: Official script
curl -fsSL https://bun.sh/install | bash
# Method 2: Homebrew
brew tap oven-sh/bun
brew install bun
# Method 3: MacPorts
sudo port install bun
# For Apple Silicon Macs
arch -arm64 brew install bun
#### Windows (WSL2)
# Install WSL2 with Ubuntu
wsl --install -d Ubuntu
# Inside WSL2
curl -fsSL https://bun.sh/install | bash
source ~/.bashrc
bun --version
Method 3: Docker
# Run Bun in Docker
docker run --rm -it oven/bun:latest
# Create Dockerfile for Bun app
cat > Dockerfile << 'EOF'
FROM oven/bun:1-alpine
WORKDIR /app
COPY package.json bun.lockb ./
RUN bun install --frozen-lockfile
COPY . .
EXPOSE 3000
CMD ["bun", "run", "start"]
EOF
4. Configuration
Environment Configuration
# Set Bun configuration directory
export BUN_INSTALL="$HOME/.bun"
export PATH="$BUN_INSTALL/bin:$PATH"
# Configure runtime behavior
export BUN_CONFIG_MAX_HTTP_HEADER_SIZE=16384
export BUN_CONFIG_NO_CLEAR_TERMINAL_ON_RELOAD=1
# Set registry mirror (for China/corporate networks)
export BUN_CONFIG_REGISTRY="https://registry.npmjs.org/"
Project Configuration
Create bunfig.toml
for project-specific configuration:
# bunfig.toml
# Package manager settings
[install]
# Use exact versions
exact = true
# Install peer dependencies
peer = true
# Install dev dependencies
dev = true
# Registry settings
[install.registry]
url = "https://registry.npmjs.org"
token = "$npm_token"
# Cache settings
[install.cache]
dir = "~/.bun/install/cache"
disable = false
# Lockfile settings
[install.lockfile]
save = true
# Build settings
[build]
target = "bun"
outdir = "./dist"
splitting = true
sourcemap = "external"
# Test settings
[test]
preload = "./test/setup.ts"
timeout = 5000
Package.json Configuration
{
"name": "my-bun-app",
"version": "1.0.0",
"type": "module",
"scripts": {
"start": "bun run server.ts",
"dev": "bun --watch run server.ts",
"build": "bun build ./src/index.ts --outdir ./dist",
"test": "bun test",
"format": "bunx prettier --write ."
},
"devDependencies": {
"bun-types": "latest"
},
"peerDependencies": {
"typescript": "^5.0.0"
}
}
TypeScript Configuration
Create tsconfig.json
:
{
"compilerOptions": {
"lib": ["ESNext"],
"module": "esnext",
"target": "esnext",
"moduleResolution": "bundler",
"moduleDetection": "force",
"allowImportingTsExtensions": true,
"noEmit": true,
"composite": true,
"strict": true,
"downlevelIteration": true,
"skipLibCheck": true,
"jsx": "react-jsx",
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"allowJs": true,
"types": [
"bun-types"
]
}
}
5. Service Management
Systemd Service Configuration
Create /etc/systemd/system/bun-app.service
:
[Unit]
Description=Bun Application
After=network.target
[Service]
Type=simple
User=bunapp
Group=bunapp
WorkingDirectory=/opt/bun-app
ExecStart=/usr/local/bin/bun run start
Restart=always
RestartSec=3
Environment=NODE_ENV=production
Environment=PORT=3000
# Security settings
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/opt/bun-app
[Install]
WantedBy=multi-user.target
# Create bun user
sudo useradd -r -s /bin/false -d /opt/bun-app bunapp
# Set permissions
sudo chown -R bunapp:bunapp /opt/bun-app
# Enable and start service
sudo systemctl daemon-reload
sudo systemctl enable --now bun-app
sudo systemctl status bun-app
Development Server
# Start development server with hot reload
bun --watch run server.ts
# Start with specific port
PORT=3000 bun run server.ts
# Start with debugging
bun --inspect run server.ts
# Start with performance profiling
bun --profile run server.ts
Process Management with PM2
# Install PM2 globally
bun install -g pm2
# Create ecosystem file
cat > ecosystem.config.js << 'EOF'
module.exports = {
apps: [{
name: 'bun-app',
interpreter: 'bun',
script: 'server.ts',
cwd: '/opt/bun-app',
instances: 'max',
exec_mode: 'cluster',
env: {
NODE_ENV: 'production',
PORT: 3000
},
error_file: './logs/err.log',
out_file: './logs/out.log',
log_file: './logs/combined.log',
time: true
}]
};
EOF
# Start with PM2
pm2 start ecosystem.config.js
pm2 save
pm2 startup
6. Troubleshooting
Common Issues
1. Installation failures:
# Check system architecture
uname -m
# Download correct binary
# x64 for Intel/AMD
# aarch64 for ARM64
# Manual installation fallback
curl -fsSL https://bun.sh/install | bash -s "bun-v1.0.0"
2. Package installation issues:
# Clear cache
bun pm cache rm
# Install with verbose output
bun install --verbose
# Use different registry
bunx --registry https://registry.npmmirror.com install
3. Module resolution errors:
# Check module resolution
bun repl
> import.meta.resolve("package-name")
# Debug module loading
BUN_DEBUG=1 bun run script.ts
# Clear module cache
rm -rf ~/.bun/install/cache
4. Performance issues:
# Profile application
bun --profile run server.ts
# Check memory usage
bun --print process.memoryUsage()
# Increase memory limit
ulimit -v unlimited
Debug Information
# Get Bun information
bun --version
bun --revision
# Check installation
which bun
ls -la ~/.bun/bin/
# Environment variables
bun --print process.env
# Test JavaScript engine
bun eval 'console.log(process.versions)'
7. Security Considerations
Runtime Security
# Run with limited permissions
bun run --no-install server.ts
# Disable shell access
bun run --no-shell server.ts
# Use strict mode
cat > server.ts << 'EOF'
"use strict";
// Application code here
EOF
Package Security
# Audit dependencies
bunx npm audit
# Check for vulnerabilities
bunx snyk test
# Lock dependency versions
bun install --frozen-lockfile
# Verify package integrity
bun pm hash
Production Deployment
# Create production build
bun build ./src/index.ts \
--target=bun \
--minify \
--sourcemap=external \
--outdir=./dist
# Set production environment
export NODE_ENV=production
# Disable source maps in production
export BUN_CONFIG_DISABLE_SOURCEMAPS=1
Secure Service Configuration
# Enhanced systemd security
[Service]
# ... existing configuration ...
# Security hardening
CapabilityBoundingSet=
SystemCallFilter=@system-service
SystemCallErrorNumber=EPERM
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true
RestrictRealtime=true
RestrictNamespaces=true
RestrictSUIDSGID=true
RemoveIPC=true
PrivateDevices=true
8. Performance Tuning
Runtime Optimization
# Enable JIT optimizations
export BUN_JSC_forceJIT=1
# Configure garbage collection
export BUN_JSC_gcMaxHeapSize=2048
# Use native code generation
export BUN_JSC_useBBQJIT=1
export BUN_JSC_useOMGJIT=1
# Optimize for startup time
export BUN_JSC_useJIT=0 # Disable JIT for faster startup
Application Performance
// Use Bun's optimized APIs
import { serve } from "bun";
const server = serve({
port: 3000,
fetch(request) {
return new Response("Hello from Bun!");
},
// Enable compression
compression: true,
// Set max request body size
maxRequestBodySize: 1024 * 1024 * 10, // 10MB
});
// Use native SQLite
import { Database } from "bun:sqlite";
const db = new Database("mydb.sqlite");
// Use Web Streams API
const file = Bun.file("large-file.txt");
const stream = file.stream();
Build Optimization
# Production build with optimizations
bun build ./src/index.ts \
--target=bun \
--minify \
--splitting \
--external react \
--external react-dom \
--outdir=./dist
# Bundle for browsers
bun build ./src/browser.ts \
--target=browser \
--minify \
--splitting \
--format=esm \
--outdir=./public
9. Backup and Restore
Project Backup
#!/bin/bash
# backup-bun-project.sh
PROJECT_DIR="/opt/bun-app"
BACKUP_DIR="/var/backups/bun"
DATE=$(date +%Y%m%d_%H%M%S)
mkdir -p $BACKUP_DIR
# Backup project files
tar -czf $BACKUP_DIR/bun_project_$DATE.tar.gz \
-C $PROJECT_DIR \
--exclude='node_modules' \
--exclude='.git' \
--exclude='dist' \
.
# Backup lockfile separately
cp $PROJECT_DIR/bun.lockb $BACKUP_DIR/bun.lockb.$DATE
echo "Project backup completed: $BACKUP_DIR/bun_project_$DATE.tar.gz"
Dependency Management
# Generate lockfile
bun install --yarn
# Verify lockfile integrity
bun install --frozen-lockfile
# Export dependency tree
bun pm ls --all > dependencies.txt
# Backup global packages
bun pm ls -g > global-packages.txt
Migration from Node.js
#!/bin/bash
# migrate-from-node.sh
# Convert package-lock.json to bun.lockb
bun install
# Update scripts in package.json
sed -i 's/node /bun /g' package.json
sed -i 's/npm run/bun run/g' package.json
sed -i 's/npx /bunx /g' package.json
# Test compatibility
bun test
10. System Requirements
Minimum Requirements
Recommended Requirements
Enterprise Requirements
11. Support
Official Resources
Community Support
12. Contributing
How to Contribute
1. Fork the repository on GitHub
2. Create a feature branch
3. Submit pull request
4. Follow Zig and TypeScript coding standards
5. Include tests and benchmarks
Development Setup
# Clone repository
git clone https://github.com/oven-sh/bun.git
cd bun
# Install Zig
curl -fsSL https://ziglang.org/download/0.11.0/zig-linux-x86_64-0.11.0.tar.xz | tar xJ
# Build Bun
make setup
make build
# Run tests
make test
13. License
Bun is licensed under the MIT License.
Key points:
14. Acknowledgments
Credits
15. Version History
Recent Releases
Major Features by Version
16. Appendices
A. Quick Start Examples
// server.ts - HTTP server
import { serve } from "bun";
serve({
port: 3000,
fetch(request) {
const url = new URL(request.url);
if (url.pathname === "/") {
return new Response("Welcome to Bun!");
}
if (url.pathname === "/json") {
return Response.json({ message: "Hello from Bun!" });
}
return new Response("Not found", { status: 404 });
},
});
console.log("Server running at http://localhost:3000");
B. Testing Example
// math.test.ts
import { expect, test, describe } from "bun:test";
describe("math operations", () => {
test("addition", () => {
expect(2 + 2).toBe(4);
});
test("async test", async () => {
const result = await Promise.resolve(42);
expect(result).toBe(42);
});
});
// Run tests: bun test
C. Bundler Example
// build.ts
await Bun.build({
entrypoints: ["./src/index.ts"],
outdir: "./dist",
target: "browser",
splitting: true,
sourcemap: "external",
minify: {
whitespace: true,
identifiers: true,
syntax: true,
},
external: ["react", "react-dom"],
});
D. SQLite Example
// database.ts
import { Database } from "bun:sqlite";
const db = new Database("myapp.db");
// Create table
db.run(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL
)
`);
// Insert data
const insert = db.prepare("INSERT INTO users (name, email) VALUES (?, ?)");
insert.run("Alice", "alice@example.com");
// Query data
const users = db.query("SELECT * FROM users").all();
console.log(users);
// Close database
db.close();
E. Performance Comparison
# Benchmark script
cat > bench.js << 'EOF'
console.time("startup");
console.log("Hello, World!");
console.timeEnd("startup");
EOF
# Compare startup times
time bun bench.js
time node bench.js
time deno run bench.js
---
For more information and updates, visit https://github.com/howtomgr/bun