---
name: bun-runtime-2065d1d333d6
user-invocable: false
description: 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.
allowed-tools:
  - Read
  - Write
  - Edit
  - Bash
  - Grep
  - Glob
---

# 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


---
Source attribution: TheBushidoCollective
Original project: https://github.com/TheBushidoCollective/han/blob/19caa51d5fd144ef6b2764f2332f4c856aa5d1af/plugins/tools/bun/skills/bun-runtime/SKILL.md
License: Apache-2.0
License information: https://www.apache.org/licenses/LICENSE-2.0
Original upstream instructions; downloaded from Mega AI Hub.

## Upstream license notice

# Functional Source License, Version 1.1, ALv2 Future License

## Abbreviation

FSL-1.1-ALv2

## Notice

Copyright 2025 The Bushido Collective

## Terms and Conditions

### Licensor ("We")

The party offering the Software under these Terms and Conditions.

### The Software

The "Software" is each version of the software that we make available under
these Terms and Conditions, as indicated by our inclusion of these Terms and
Conditions with the Software.

### License Grant

Subject to your compliance with this License Grant and the Patents,
Redistribution and Trademark clauses below, we hereby grant you the right to
use, copy, modify, create derivative works, publicly perform, publicly display
and redistribute the Software for any Permitted Purpose identified below.

### Permitted Purpose

A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
means making the Software available to others in a commercial product or
service that:

1. substitutes for the Software;

2. substitutes for any other product or service we offer using the Software
   that exists as of the date we make the Software available; or

3. offers the same or substantially similar functionality as the Software.

Permitted Purposes specifically include using the Software:

1. for your internal use and access;

2. for non-commercial education;

3. for non-commercial research; and

4. in connection with professional services that you provide to a licensee
   using the Software in accordance with these Terms and Conditions.

### Patents

To the extent your use for a Permitted Purpose would necessarily infringe our
patents, the license grant above includes a license under our patents. If you
make a claim against any party that the Software infringes or contributes to
the infringement of any patent, then your patent license to the Software ends
immediately.

### Redistribution

The Terms and Conditions apply to all copies, modifications and derivatives of
the Software.

If you redistribute any copies, modifications or derivatives of the Software,
you must include a copy of or a link to these Terms and Conditions and not
remove any copyright notices provided in or with the Software.

### Disclaimer

THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.

IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.

### Trademarks

Except for displaying the License Details and identifying us as the origin of
the Software, you have no right under these Terms and Conditions to use our
trademarks, trade names, service marks or product names.

## Grant of Future License

We hereby irrevocably grant you an additional license to use the Software under
the Apache License, Version 2.0 that is effective on the second anniversary of
the date we make the Software available. On or after that date, you may use the
Software under the Apache License, Version 2.0, in which case the following
will apply:

Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License.

You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.



# Mega AI Hub resource metadata

Creator / publisher: TheBushidoCollective
Original project: https://github.com/TheBushidoCollective/han/blob/19caa51d5fd144ef6b2764f2332f4c856aa5d1af/plugins/tools/bun/skills/bun-runtime/SKILL.md
Attribution basis: Source repository record

Fields of work: Development & Engineering
Roles: Backend Developer, DevOps / SRE, Full-Stack Developer
Specialties: Backend
Tools: Bun
Country applicability: Country not specified
Classification basis: Source catalog labels
Instruction SHA-256: 7d87c6374cb2a548db94d19f22274bfee49049d8757728260aee54859a71b4f7
