<< All versions
Skill v1.0.1
currentAutomated scan100/100hoodini/ai-agents-skills/bun
1 files
──Details
PublishedJune 28, 2026 at 01:01 AM
Content Hashsha256:7c5deb273e49ca7e...
Git SHA83e2083e3ec8
Bump Typepatch
──Files
Files (1 file, 11.1 KB)
SKILL.md11.1 KBactive
SKILL.md · 536 lines · 11.1 KB
version: "1.0.1" name: bun description: Build fast applications with Bun JavaScript runtime. Use when creating Bun projects, using Bun APIs, bundling, testing, or optimizing Node.js alternatives. Triggers on Bun, Bun runtime, bun.sh, bunx, Bun serve, Bun test, JavaScript runtime.
Bun - The Fast JavaScript Runtime
Build and run JavaScript/TypeScript applications with Bun's all-in-one toolkit.
Quick Start
bash
# Install Bun (macOS, Linux, WSL)curl -fsSL https://bun.sh/install | bash# Windowspowershell -c "irm bun.sh/install.ps1 | iex"# Create new projectbun init# Run TypeScript directly (no build step!)bun run index.ts# Install packages (faster than npm)bun install# Run scriptsbun run dev
Package Management
bash
# Install dependenciesbun install # Install all from package.jsonbun add express # Add dependencybun add -d typescript # Add dev dependencybun add -g serve # Add global package# Remove packagesbun remove express# Update packagesbun update# Run package binariesbunx prisma generate # Like npx but fasterbunx create-next-app# Lockfilebun install --frozen-lockfile # CI mode
bun.lockb vs package-lock.json
bash
# Bun uses binary lockfile (bun.lockb) - much faster# To generate yarn.lock for compatibility:bun install --yarn# Import from other lockfilesbun install # Auto-detects package-lock.json, yarn.lock
Bun Runtime
Run Files
bash
# Run any filebun run index.ts # TypeScriptbun run index.js # JavaScriptbun run index.jsx # JSX# Watch modebun --watch run index.ts# Hot reloadbun --hot run server.ts
Built-in APIs
typescript
// File I/O (super fast)const file = Bun.file('data.json');const content = await file.text();const json = await file.json();const bytes = await file.arrayBuffer();// Write filesawait Bun.write('output.txt', 'Hello, Bun!');await Bun.write('data.json', JSON.stringify({ key: 'value' }));await Bun.write('image.png', await fetch('https://example.com/img.png'));// File metadataconst file = Bun.file('data.json');console.log(file.size); // bytesconsole.log(file.type); // MIME typeconsole.log(file.lastModified);// Glob filesconst glob = new Bun.Glob('**/*.ts');for await (const file of glob.scan('.')) {console.log(file);}
HTTP Server
typescript
// Simple serverconst server = Bun.serve({port: 3000,fetch(req) {const url = new URL(req.url);if (url.pathname === '/') {return new Response('Hello, Bun!');}if (url.pathname === '/json') {return Response.json({ message: 'Hello!' });}return new Response('Not Found', { status: 404 });},});console.log(`Server running at http://localhost:${server.port}`);
Advanced Server
typescript
Bun.serve({port: 3000,// Main request handlerasync fetch(req, server) {const url = new URL(req.url);// WebSocket upgradeif (url.pathname === '/ws') {const upgraded = server.upgrade(req, {data: { userId: '123' }, // Attach data to socket});if (upgraded) return undefined;}// Static filesif (url.pathname.startsWith('/static/')) {const filePath = `./public${url.pathname}`;const file = Bun.file(filePath);if (await file.exists()) {return new Response(file);}}// JSON APIif (url.pathname === '/api/data' && req.method === 'POST') {const body = await req.json();return Response.json({ received: body });}return new Response('Not Found', { status: 404 });},// WebSocket handlerswebsocket: {open(ws) {console.log('Client connected:', ws.data.userId);ws.subscribe('chat'); // Pub/sub},message(ws, message) {// Broadcast to all subscribersws.publish('chat', message);},close(ws) {console.log('Client disconnected');},},// Error handlingerror(error) {return new Response(`Error: ${error.message}`, { status: 500 });},});
WebSocket Client
typescript
const ws = new WebSocket('ws://localhost:3000/ws');ws.onopen = () => {ws.send('Hello, server!');};ws.onmessage = (event) => {console.log('Received:', event.data);};
Bun APIs
SQLite (Built-in)
typescript
import { Database } from 'bun:sqlite';const db = new Database('mydb.sqlite');// Create tabledb.run(`CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT NOT NULL,email TEXT UNIQUE)`);// Insertconst insert = db.prepare('INSERT INTO users (name, email) VALUES (?, ?)');insert.run('Alice', 'alice@example.com');// Queryconst query = db.prepare('SELECT * FROM users WHERE id = ?');const user = query.get(1);// All resultsconst allUsers = db.prepare('SELECT * FROM users').all();// Transactionconst insertMany = db.transaction((users) => {for (const user of users) {insert.run(user.name, user.email);}});insertMany([{ name: 'Bob', email: 'bob@example.com' },{ name: 'Charlie', email: 'charlie@example.com' },]);
Password Hashing (Built-in)
typescript
// Hash passwordconst hash = await Bun.password.hash('mypassword', {algorithm: 'argon2id', // or 'bcrypt'memoryCost: 65536, // 64 MBtimeCost: 2,});// Verify passwordconst isValid = await Bun.password.verify('mypassword', hash);
Spawn Processes
typescript
// Spawn processconst proc = Bun.spawn(['ls', '-la'], {cwd: '/home/user',env: { ...process.env, MY_VAR: 'value' },stdout: 'pipe',});const output = await new Response(proc.stdout).text();console.log(output);// Spawn syncconst result = Bun.spawnSync(['echo', 'hello']);console.log(result.stdout.toString());// Shell commandconst { stdout } = Bun.spawn({cmd: ['sh', '-c', 'echo $HOME'],stdout: 'pipe',});
Hashing & Crypto
typescript
// Hash stringsconst hash = Bun.hash('hello world'); // Wyhash (fast)// Crypto hashesconst sha256 = new Bun.CryptoHasher('sha256');sha256.update('data');const digest = sha256.digest('hex');// One-linerconst md5 = Bun.CryptoHasher.hash('md5', 'data', 'hex');// HMACconst hmac = Bun.CryptoHasher.hmac('sha256', 'secret-key', 'data', 'hex');
Bundler
bash
# Bundle for browserbun build ./src/index.ts --outdir ./dist# Bundle optionsbun build ./src/index.ts \--outdir ./dist \--minify \--sourcemap \--target browser \--splitting \--entry-naming '[dir]/[name]-[hash].[ext]'
Build API
typescript
const result = await Bun.build({entrypoints: ['./src/index.ts'],outdir: './dist',minify: true,sourcemap: 'external',target: 'browser', // 'bun' | 'node' | 'browser'splitting: true,naming: {entry: '[dir]/[name]-[hash].[ext]',chunk: '[name]-[hash].[ext]',asset: '[name]-[hash].[ext]',},external: ['react', 'react-dom'],define: {'process.env.NODE_ENV': JSON.stringify('production'),},loader: {'.png': 'file','.svg': 'text',},});if (!result.success) {console.error('Build failed:', result.logs);}
Testing
typescript
// test.tsimport { describe, test, expect, beforeAll, afterAll, mock } from 'bun:test';describe('Math operations', () => {test('addition', () => {expect(1 + 1).toBe(2);});test('array contains', () => {expect([1, 2, 3]).toContain(2);});test('object matching', () => {expect({ name: 'Alice', age: 30 }).toMatchObject({ name: 'Alice' });});test('async test', async () => {const result = await Promise.resolve(42);expect(result).toBe(42);});test('throws error', () => {expect(() => {throw new Error('fail');}).toThrow('fail');});});// Mockingconst mockFn = mock(() => 'mocked');mockFn();expect(mockFn).toHaveBeenCalled();// Mock modulesmock.module('./database', () => ({query: mock(() => [{ id: 1 }]),}));
bash
# Run testsbun test# Watch modebun test --watch# Specific filebun test user.test.ts# Coveragebun test --coverage
Node.js Compatibility
typescript
// Most Node.js APIs work out of the boximport fs from 'fs';import path from 'path';import { createServer } from 'http';import express from 'express';// Bun implements Node.js APIsconst data = fs.readFileSync('file.txt', 'utf-8');const fullPath = path.join(__dirname, 'file.txt');// Express works!const app = express();app.get('/', (req, res) => res.send('Hello!'));app.listen(3000);
Node.js vs Bun APIs
typescript
// Node.js wayimport { readFile } from 'fs/promises';const content = await readFile('file.txt', 'utf-8');// Bun way (faster)const content = await Bun.file('file.txt').text();// Node.js cryptoimport crypto from 'crypto';const hash = crypto.createHash('sha256').update('data').digest('hex');// Bun way (faster)const hash = Bun.CryptoHasher.hash('sha256', 'data', 'hex');
Environment Variables
typescript
// .env file support (built-in, no dotenv needed!)// .env// DATABASE_URL=postgres://localhost/db// API_KEY=secret// Access env varsconst dbUrl = Bun.env.DATABASE_URL;const apiKey = process.env.API_KEY; // Also works// bunfig.toml for Bun config// [run]// preload = ["./setup.ts"]
HTTP Client
typescript
// Fetch (optimized in Bun)const response = await fetch('https://api.example.com/data', {method: 'POST',headers: {'Content-Type': 'application/json','Authorization': 'Bearer token',},body: JSON.stringify({ key: 'value' }),});const data = await response.json();// Streaming responseconst response = await fetch('https://api.example.com/stream');const reader = response.body?.getReader();while (true) {const { done, value } = await reader!.read();if (done) break;console.log(new TextDecoder().decode(value));}
Project Structure
my-bun-project/├── src/│ ├── index.ts # Entry point│ ├── routes/│ │ └── api.ts│ └── lib/│ └── database.ts├── tests/│ └── index.test.ts├── public/│ └── static files├── package.json├── bunfig.toml # Bun config (optional)├── tsconfig.json└── .env
bunfig.toml
toml
[install]# Use exact versions by defaultexact = true# Registryregistry = "https://registry.npmjs.org"[run]# Scripts to run before `bun run`preload = ["./instrumentation.ts"][test]# Test configurationcoverage = truecoverageDir = "coverage"[bundle]# Default bundle configminify = truesourcemap = "external"
Performance Comparison
| Operation | Node.js | Bun | Speedup | |
|---|---|---|---|---|
| Start time | ~40ms | ~7ms | 5.7x | |
| Package install | ~10s | ~1s | 10x | |
| File read | baseline | faster | 10x | |
| HTTP server | baseline | faster | 4x | |
| SQLite | external | built-in | 3x | |
| TypeScript | compile needed | native | ∞ |
Resources
- Bun Docs: https://bun.sh/docs
- Bun API Reference: https://bun.sh/docs/api
- Bun Discord: https://bun.sh/discord
- GitHub: https://github.com/oven-sh/bun