DEV Community

Alex Spinov
Alex Spinov

Posted on

Bun Has a Free API — Here's How to Use the All-in-One JavaScript Runtime

Bun is a fast all-in-one JavaScript runtime that includes a bundler, test runner, and package manager. It is 3-4x faster than Node.js for many operations.

Installation

curl -fsSL https://bun.sh/install | bash
Enter fullscreen mode Exit fullscreen mode

Running JavaScript

bun run index.ts    # Direct TypeScript execution
bun run index.js    # JavaScript
bun run index.jsx   # JSX support built-in
Enter fullscreen mode Exit fullscreen mode

HTTP Server

const server = Bun.serve({
  port: 3000,
  async fetch(req) {
    const url = new URL(req.url);

    if (url.pathname === "/api/hello") {
      return Response.json({ message: "Hello from Bun!" });
    }

    if (url.pathname === "/api/posts" && req.method === "POST") {
      const body = await req.json();
      return Response.json({ created: body }, { status: 201 });
    }

    return new Response("Not Found", { status: 404 });
  }
});

console.log(`Server running at ${server.url}`);
Enter fullscreen mode Exit fullscreen mode

File I/O

// Read file
const content = await Bun.file("data.json").text();
const data = JSON.parse(content);

// Write file
await Bun.write("output.json", JSON.stringify(data, null, 2));

// Stream large files
const file = Bun.file("large.csv");
const stream = file.stream();
Enter fullscreen mode Exit fullscreen mode

Package Manager (faster than npm)

bun install              # Install dependencies
bun add express          # Add package
bun add -d vitest        # Dev dependency
bun remove lodash        # Remove
bun update               # Update all
Enter fullscreen mode Exit fullscreen mode

Test Runner

// math.test.ts
import { expect, test, describe } from "bun:test";

describe("math", () => {
  test("addition", () => {
    expect(2 + 2).toBe(4);
  });

  test("async", async () => {
    const result = await fetchData();
    expect(result).toBeDefined();
  });
});
Enter fullscreen mode Exit fullscreen mode
bun test
bun test --coverage
Enter fullscreen mode Exit fullscreen mode

SQLite (Built-in)

import { Database } from "bun:sqlite";

const db = new Database("app.db");
db.run("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)");

const insert = db.prepare("INSERT INTO users (name, email) VALUES (?, ?)");
insert.run("Alex", "alex@dev.com");

const users = db.prepare("SELECT * FROM users").all();
console.log(users);
Enter fullscreen mode Exit fullscreen mode

Bundler

bun build ./src/index.ts --outdir ./dist --target browser --minify
Enter fullscreen mode Exit fullscreen mode

Need to extract or automate web content at scale? Check out my web scraping tools on Apify — no coding required. Or email me at spinov001@gmail.com for custom solutions.

Top comments (0)