bun-runtime
Use when working with Bun's runtime APIs including file I/O, HTTP servers, and native APIs. Covers modern JavaScript/TypeScript execution in Bun's fast runtime environment.
What this skill does
# Bun Runtime APIs
Use this skill when working with Bun's runtime environment, including file system operations, HTTP servers, environment variables, and Bun-specific APIs.
## Key Concepts
### Bun Globals
Bun provides several global APIs that are optimized for performance:
- `Bun.file()` - Fast file reading with automatic content-type detection
- `Bun.write()` - High-performance file writing
- `Bun.serve()` - Ultra-fast HTTP server
- `Bun.env` - Type-safe environment variables
- `Bun.$` - Shell command execution with template literals
### File I/O
Bun's file APIs are significantly faster than Node.js equivalents:
```typescript
// Reading files
const file = Bun.file("./data.json");
const text = await file.text();
const json = await file.json();
const arrayBuffer = await file.arrayBuffer();
// Writing files
await Bun.write("output.txt", "Hello, Bun!");
await Bun.write("data.json", { key: "value" });
// Streaming large files
const file = Bun.file("large-file.txt");
const stream = file.stream();
```
### HTTP Server
Bun.serve() provides exceptional performance:
```typescript
Bun.serve({
port: 3000,
fetch(req) {
const url = new URL(req.url);
if (url.pathname === "/") {
return new Response("Hello, Bun!");
}
if (url.pathname === "/api/data") {
return Response.json({ message: "Fast API response" });
}
return new Response("Not Found", { status: 404 });
},
});
```
### WebSocket Support
Built-in WebSocket support without external dependencies:
```typescript
Bun.serve({
port: 3000,
fetch(req, server) {
if (server.upgrade(req)) {
return; // WebSocket upgrade successful
}
return new Response("Expected WebSocket connection", { status: 400 });
},
websocket: {
message(ws, message) {
console.log("Received:", message);
ws.send(`Echo: ${message}`);
},
open(ws) {
console.log("Client connected");
},
close(ws) {
console.log("Client disconnected");
},
},
});
```
## Best Practices
### Use Native APIs
Prefer Bun's native APIs over Node.js equivalents for better performance:
```typescript
// Good - Use Bun.file()
const data = await Bun.file("./data.json").json();
// Avoid - Don't use fs from Node.js when Bun alternatives exist
import fs from "fs/promises";
const data = JSON.parse(await fs.readFile("./data.json", "utf-8"));
```
### Type Safety with Environment Variables
Use type-safe environment variable access:
```typescript
// Good - Type-safe access
const apiKey = Bun.env.API_KEY;
// Also valid - process.env works but Bun.env is preferred
const port = process.env.PORT ?? "3000";
```
### Efficient Shell Commands
Use `Bun.$` for shell command execution:
```typescript
// Execute shell commands safely
import { $ } from "bun";
const output = await $`ls -la`.text();
const gitBranch = await $`git branch --show-current`.text();
// With error handling
try {
await $`npm run build`;
} catch (error) {
console.error("Build failed:", error);
}
```
### Password Hashing
Use built-in password hashing:
```typescript
const password = "super-secret";
// Hash a password
const hash = await Bun.password.hash(password);
// Verify a password
const isMatch = await Bun.password.verify(password, hash);
```
## Common Patterns
### API Server with JSON
```typescript
interface User {
id: number;
name: string;
}
const users: User[] = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
];
Bun.serve({
port: 3000,
fetch(req) {
const url = new URL(req.url);
if (url.pathname === "/api/users") {
return Response.json(users);
}
if (url.pathname.startsWith("/api/users/")) {
const id = parseInt(url.pathname.split("/")[3]);
const user = users.find((u) => u.id === id);
if (!user) {
return Response.json({ error: "User not found" }, { status: 404 });
}
return Response.json(user);
}
return Response.json({ error: "Not found" }, { status: 404 });
},
});
```
### File Upload Handler
```typescript
Bun.serve({
port: 3000,
async fetch(req) {
if (req.method === "POST" && new URL(req.url).pathname === "/upload") {
const formData = await req.formData();
const file = formData.get("file") as File;
if (!file) {
return Response.json({ error: "No file provided" }, { status: 400 });
}
await Bun.write(`./uploads/${file.name}`, file);
return Response.json({
message: "File uploaded successfully",
filename: file.name,
size: file.size,
});
}
return new Response("Method not allowed", { status: 405 });
},
});
```
### Reading Configuration Files
```typescript
// Read and parse JSON config
const config = await Bun.file("./config.json").json();
// Read TOML (Bun has built-in TOML support)
const tomlConfig = await Bun.file("./config.toml").text();
// Read environment-specific config
const env = Bun.env.NODE_ENV ?? "development";
const envConfig = await Bun.file(`./config.${env}.json`).json();
```
## Anti-Patterns
### Don't Mix Node.js and Bun APIs Unnecessarily
```typescript
// Bad - Mixing APIs without reason
import fs from "fs/promises";
const data1 = await fs.readFile("file1.txt", "utf-8");
const data2 = await Bun.file("file2.txt").text();
// Good - Use consistent APIs
const data1 = await Bun.file("file1.txt").text();
const data2 = await Bun.file("file2.txt").text();
```
### Don't Ignore Error Handling
```typescript
// Bad - No error handling
const data = await Bun.file("./might-not-exist.json").json();
// Good - Proper error handling
try {
const file = Bun.file("./might-not-exist.json");
if (await file.exists()) {
const data = await file.json();
} else {
console.error("File not found");
}
} catch (error) {
console.error("Failed to read file:", error);
}
```
### Don't Block the Event Loop
```typescript
// Bad - Synchronous file reading blocks
import fs from "fs";
const data = fs.readFileSync("large-file.txt", "utf-8");
// Good - Async operations
const data = await Bun.file("large-file.txt").text();
```
## Related Skills
- **bun-testing**: Testing Bun applications with built-in test runner
- **bun-bundler**: Building and bundling with Bun's fast bundler
- **bun-package-manager**: Managing dependencies with Bun's package manager
Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.