Bun is a fast, all-in-one JavaScript runtime that aims to replace Node.js, npm, and more.
Installation
# macOS/Linux
curl -fsSL https://bun.sh/install | bash
# Windows (WSL)
npm install -g bun
# Verify installation
bun --version
Running Scripts
# Run JavaScript/TypeScript
bun index.ts
# Run with watch mode
bun --watch index.ts
# Hot reload
bun --hot server.ts
HTTP Server
// server.ts
const server = Bun.serve({
port: 3000,
fetch(request) {
const url = new URL(request.url);
if (url.pathname === '/') {
return new Response('Hello from Bun!');
}
if (url.pathname === '/api/data') {
return Response.json({ message: 'API response', timestamp: Date.now() });
}
return new Response('Not Found', { status: 404 });
},
});
console.log(`Server running at http://localhost:${server.port}`);
File System Operations
// Ultra-fast file operations
const file = Bun.file('data.json');
// Read file
const text = await file.text();
const json = await file.json();
const buffer = await file.arrayBuffer();
// Write file
await Bun.write('output.txt', 'Hello, Bun!');
await Bun.write('data.json', JSON.stringify({ key: 'value' }));
// Stream large files
const stream = file.stream();
for await (const chunk of stream) {
console.log(chunk);
}
SQLite Database
import { Database } from 'bun:sqlite';
const db = new Database('mydb.sqlite');
// Create table
db.run(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE
)
`);
// Insert
const insert = db.prepare('INSERT INTO users (name, email) VALUES (?, ?)');
insert.run('John Doe', 'john@example.com');
// Query
const query = db.prepare('SELECT * FROM users WHERE email = ?');
const user = query.get('john@example.com');
// Query all
const users = db.prepare('SELECT * FROM users').all();
// Transaction
const insertMany = db.transaction((users) => {
for (const user of users) {
insert.run(user.name, user.email);
}
});
insertMany([
{ name: 'Jane', email: 'jane@example.com' },
{ name: 'Bob', email: 'bob@example.com' },
]);
Testing
// math.test.ts
import { expect, test, describe } from 'bun:test';
describe('Math operations', () => {
test('addition', () => {
expect(2 + 2).toBe(4);
});
test('multiplication', () => {
expect(3 * 4).toBe(12);
});
});
// Run tests
// bun test
Environment Variables
// Access environment variables
const apiKey = process.env.API_KEY;
const dbUrl = Bun.env.DATABASE_URL;
// Load from .env file (automatic)
console.log(Bun.env.SECRET_KEY);
Building/Bundling
# Bundle for production
bun build ./index.ts --outdir ./dist --target node
# Minify
bun build ./index.ts --minify --outfile dist/bundle.js
# Watch mode
bun build ./index.ts --watch
Package Management
# Install dependencies (faster than npm)
bun install
# Add package
bun add express
bun add -d @types/express
# Remove package
bun remove express
# Update packages
bun update
# Run script
bun run dev
WebSocket Server
const server = Bun.serve({
port: 3000,
fetch(req, server) {
const url = new URL(req.url);
if (url.pathname === '/ws') {
const success = server.upgrade(req);
if (success) return undefined;
}
return new Response('WebSocket endpoint: /ws');
},
websocket: {
message(ws, message) {
console.log('Received:', message);
ws.send(`Echo: ${message}`);
},
open(ws) {
console.log('Client connected');
ws.send('Welcome!');
},
close(ws) {
console.log('Client disconnected');
},
},
});
Password Hashing
const password = 'super-secret';
// Hash password
const hash = await Bun.password.hash(password);
// Verify password
const isValid = await Bun.password.verify(password, hash);
console.log(isValid); // true
Transpiling
// Transpile TypeScript
const transpiler = new Bun.Transpiler({
loader: 'tsx',
});
const code = `
const greeting: string = 'Hello';
export default greeting;
`;
const js = transpiler.transformSync(code);
console.log(js);
Process Spawning
// Spawn subprocess
const proc = Bun.spawn(['ls', '-la'], {
cwd: '/tmp',
env: { ...process.env, CUSTOM: 'value' },
stdout: 'pipe',
});
const output = await new Response(proc.stdout).text();
console.log(output);
await proc.exited;
Performance Comparison
// Bun is significantly faster for:
// - Server startup time
// - Package installation
// - File I/O operations
// - Module resolution
// - Built-in APIs
// Example: Reading large file
console.time('read');
const file = Bun.file('large-file.json');
const data = await file.json();
console.timeEnd('read'); // Much faster than fs.readFile
React with Bun
// server.tsx
const server = Bun.serve({
port: 3000,
async fetch(req) {
const App = () => (
<html>
<body>
<h1>Hello from Bun + React!</h1>
</body>
</html>
);
return new Response(
'<!DOCTYPE html>' + (await Bun.renderToReadableStream(<App />)),
{
headers: { 'Content-Type': 'text/html' },
}
);
},
});
Bun offers impressive performance gains and a better developer experience for modern JavaScript.
Posted onnodejswith tags: