The Complete Bun Guide | Ultra-Fast JavaScript Runtime, Package Manager, Bundler, Tests, and Production Use

The Complete Bun Guide | Ultra-Fast JavaScript Runtime, Package Manager, Bundler, Tests, and Production Use

What this post covers

This is a complete guide to fast JavaScript development with Bun. It covers a Node.js alternative, fast package installs, the built-in bundler, and the test runner—with practical examples throughout.

From the field: After switching from Node.js to Bun, we saw package installs roughly 10× faster and tests about 5× faster.

Introduction: “Node.js feels slow”

Real-world scenarios

Scenario 1: npm install is too slow

npm is slow. Bun is roughly 10× faster. Scenario 2: Bundler setup is painful

Webpack is complex. Bun ships with a built-in bundler. Scenario 3: Tests are slow

Jest is slow. Bun’s test runner is roughly 5× faster.


1. What is Bun?

Core characteristics

Bun is an ultra-fast JavaScript runtime. Key benefits:

  • Speed: about 4× faster than Node.js
  • All-in-one: runtime + package manager + bundler + tests
  • Node.js compatibility: largely compatible
  • TypeScript: native support
  • Web APIs: fetch, WebSocket built in Performance comparison (illustrative):
  • Node.js: 100ms
  • Deno: 80ms
  • Bun: 25ms

2. Installation and basics

Install

# macOS/Linux
curl -fsSL https://bun.sh/install | bash
# Windows
powershell -c "irm bun.sh/install.ps1 | iex"

Basic commands

# Run a file
bun run index.ts
# REPL
bun
# Version
bun --version

3. Package management

Installing packages

# Install dependencies
bun install
# Add a package
bun add express
bun add -d typescript
# Remove a package
bun remove express
# Global install
bun add -g typescript

Speed comparison (illustrative):

  • npm: 60s
  • pnpm: 20s
  • bun: 6s

4. Web servers

HTTP server

The following is a detailed TypeScript example. It branches on the URL path with conditionals—walk through each part to see the flow.

// server.ts
const server = Bun.serve({
  port: 3000,
  fetch(req) {
    const url = new URL(req.url);
    if (url.pathname === '/') {
      return new Response('Hello Bun!');
    }
    if (url.pathname === '/api/users') {
      return Response.json([
        { id: 1, name: 'John' },
        { id: 2, name: 'Jane' },
      ]);
    }
    return new Response('Not Found', { status: 404 });
  },
});
console.log(`Server running on http://localhost:${server.port}`);

Using Express

import express from 'express';
const app = express();
app.get('/', (req, res) => {
  res.send('Hello Bun with Express!');
});
app.listen(3000, () => {
  console.log('Server running on :3000');
});

5. Bundler

Basic bundling

Below is a TypeScript example using async Bun.build, with minification and external source maps. Run it locally to verify behavior.

// build.ts
await Bun.build({
  entrypoints: ['./src/index.ts'],
  outdir: './dist',
  target: 'browser',
  minify: true,
  sourcemap: 'external',
});

Bundling React

This example bundles a React entry with code splitting and file loaders for assets. Inspect each option as you read.

await Bun.build({
  entrypoints: ['./src/index.tsx'],
  outdir: './dist',
  target: 'browser',
  minify: true,
  splitting: true,
  loader: {
    '.png': 'file',
    '.svg': 'file',
  },
});

6. Tests

Basic tests

// math.test.ts
import { expect, test, describe } from 'bun:test';
describe('Math', () => {
  test('add', () => {
    expect(1 + 2).toBe(3);
  });
  test('multiply', () => {
    expect(2 * 3).toBe(6);
  });
});

Async tests

Example using bun:test with fetch. Run it against a real or mocked API to confirm behavior.

import { expect, test } from 'bun:test';
test('fetch users', async () => {
  const response = await fetch('https://api.example.com/users');
  const users = await response.json();
  expect(users).toBeArray();
  expect(users.length).toBeGreaterThan(0);
});

Run tests

bun test

7. File system

Reading files

Examples of reading text, JSON, and binary with Bun.file.

// Text file
const text = await Bun.file('data.txt').text();
// JSON file
const json = await Bun.file('data.json').json();
// Binary file
const buffer = await Bun.file('image.png').arrayBuffer();

Writing files

await Bun.write('output.txt', 'Hello Bun!');
await Bun.write('data.json', JSON.stringify({ name: 'John' }));

8. Environment variables

Using .env values via process.env and Bun.env.

// .env
DATABASE_URL=postgresql://localhost:5432/mydb
API_KEY=secret123
// Usage
console.log(process.env.DATABASE_URL);
console.log(Bun.env.API_KEY);

9. Hot reload

bun --watch server.ts

10. Practical example

REST API

A TypeScript example with async handlers and conditional routing. Adjust db / usersTable to match your ORM or data layer.

// api/server.ts
const server = Bun.serve({
  port: 3000,
  async fetch(req) {
    const url = new URL(req.url);
    if (url.pathname === '/api/users' && req.method === 'GET') {
      const users = await db.select().from(usersTable);
      return Response.json(users);
    }
    if (url.pathname === '/api/users' && req.method === 'POST') {
      const body = await req.json();
      const user = await db.insert(usersTable).values(body).returning();
      return Response.json(user[0], { status: 201 });
    }
    return new Response('Not Found', { status: 404 });
  },
});

Summary and checklist

Key takeaways

  • Bun: ultra-fast JavaScript runtime
  • All-in-one: runtime + package manager + bundler + tests
  • Speed: about 4× faster than Node.js for many workloads
  • TypeScript: native support
  • Node.js compatibility: largely compatible
  • Web APIs: fetch, WebSocket built in

Checklist

  • Install Bun
  • Initialize the project
  • Implement a web server
  • Configure bundling
  • Write tests
  • Use the file system APIs
  • Deploy

  • The complete pnpm guide
  • The complete Vite 5 guide
  • The complete Vitest guide

Keywords in this post

Bun, JavaScript, Runtime, Package Manager, Bundler, Performance, Node.js

Frequently asked questions (FAQ)

Q. Can Bun fully replace Node.js?

A. In many cases, yes—but some native addons may not be compatible.

Q. Is it OK to use Bun in production?

A. Bun has reached 1.x and many projects use it in production. If you prioritize maximum maturity above all else, Node.js remains a conservative choice.

Q. Can I use npm packages?

A. Yes—most npm packages work with Bun’s compatibility layer.

Q. Is Windows supported?

A. Yes—Windows is supported.