正在加载,请稍候…

Bun:快速的全能 JavaScript 运行时与工具集

探索 Bun 作为 JavaScript 运行时、包管理器、打包器和测试运行器。与 Node.js 进行性能对比,了解何时在生产环境中使用 Bun。

Bun:快速的全能 JavaScript 运行时与工具集

Bun:快速的全能 JavaScript 运行时

Bun 是一个用 Zig 构建的快速全能 JavaScript 运行时,使用 JavaScriptCore(Safari 引擎)。它比 Node.js 快得多,并包含包管理器、打包器和测试运行器。

速度:核心特性

# 包安装对比
npm install        # ~15 秒
yarn install       # ~10 秒
bun install        # ~1.5 秒  # 快 10 倍!

# 脚本启动时间
node -e "console.log('hi')"   # ~60ms
bun -e "console.log('hi')"    # ~6ms  # 快 10 倍!

Bun:快速的全能 JavaScript 运行时与工具集 插图

HTTP 服务器

const server = Bun.serve({
  port: 3000,
  fetch(request) {
    const url = new URL(request.url);
    
    if (url.pathname === "/") {
      return new Response("Hello from Bun!");
    }
    
    if (url.pathname === "/json") {
      return Response.json({ 
        runtime: "Bun",
        version: Bun.version 
      });
    }
    
    return new Response("Not Found", { status: 404 });
  },
});

文件 I/O

// 读取文件 - 比 Node.js fs 更快
const file = Bun.file("./data.json");
const content = await file.text();
const json = await file.json();

// 写入文件
await Bun.write("./output.txt", "Hello, Bun!");
await Bun.write("./data.json", JSON.stringify({ key: "value" }));

Bun:快速的全能 JavaScript 运行时与工具集 插图

内置测试运行器

import { test, expect, describe } from "bun:test";

describe("Calculator", () => {
  test("adds two numbers", () => {
    expect(2 + 3).toBe(5);
  });
  
  test("async test", async () => {
    const res = await fetch("https://example.com");
    expect(res.ok).toBe(true);
  });
});
bun test
bun test --watch
bun test --coverage

SQLite 集成

import { Database } from "bun:sqlite";

const db = new Database(":memory:");
db.run("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)");

const insert = db.prepare("INSERT INTO users (name) VALUES (?)");
insert.run("Alice");
insert.run("Bob");

const users = db.query("SELECT * FROM users").all();
console.log(users); // [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]

Bun:快速的全能 JavaScript 运行时与工具集 插图

打包器

# 为浏览器打包 TypeScript
bun build ./src/index.ts --outdir ./dist --minify

# 或通过 API
await Bun.build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist",
  target: "browser",
  minify: true,
});

性能基准测试

操作 Node.js Bun
HTTP 请求/秒 ~85k ~170k
npm install ~15s ~1.5s
TypeScript 启动 ~100ms ~8ms
SQLite 查询/秒 ~500k ~1.2M

何时使用 Bun

  • 新项目:优秀的默认选择
  • CLI 工具:快速启动时间很重要
  • SQLite 应用:一流的 SQLite 性能
  • TypeScript 应用:原生 TS 支持,无需构建步骤

总结

Bun 已可用于生产环境,并提供了令人信服的性能优势。内置的 SQLite、测试运行器和打包器减少了工具链的复杂性。对于新的 JavaScript/TypeScript 项目,Bun 值得认真考虑。