Bun 入门:Bun.serve 零依赖启动 HTTP 服务

一、Bun 的 HTTP 服务器是内置的

用 Node.js 写一个 HTTP 接口,至少要装 express 或 http 模块。用 Bun,什么都不用装------Bun.serve 是运行时自带的 API。

typescript 复制代码
const server = Bun.serve({
    port: 8080,
    fetch(req) {
        const url = new URL(req.url);
        if (url.pathname === '/todos' && req.method === 'GET') {
            return Response.json(todos);
        }
        return new Response('Not Found', { status: 404 });
    }
});

console.log(`Server running on http://localhost:${server.port}`);

这段代码不需要 import 任何外部包。Bun.serve、Request、Response 都是 Web 标准 API。


二、TypeScript 零配置

Bun 内置 TypeScript 转译器,不需要 tsc、ts-node、tsconfig.json:

bash 复制代码
bun run server.ts

直接运行 .ts 文件。启动速度远快于 ts-node,因为 Bun 的转译器用 Zig 实现,没有冷启动延迟。


三、路由手动处理

Bun.serve 没有内置路由------路由需要自己解析:

typescript 复制代码
fetch(req) {
    const url = new URL(req.url);
    const id = url.pathname.match(/^\/todos\/(\d+)$/)?.[1];
    if (id) {
        const todo = todos.find(t => t.id === parseInt(id));
        return Response.json(todo);
    }
}

对于小项目,手动路由比上框架更透明。等路由多了再用 Elysia 或 Hono。


四、和 Node.js 对比

Node.js + Express 需要 npm install express + ts-node。Bun 零依赖,内置 TypeScript 支持,API 遵循 Web 标准。HTTP 吞吐量约为 Node.js 的 3-5 倍。


五、总结

  1. Bun.serve 零依赖启动 HTTP 服务,API 遵循 Web 标准
  2. TypeScript 开箱即用,无需配置
  3. 路由需手动解析,小项目够用
  4. 前端也可以用同样的 fetch API 调用后端
相关推荐
theMuseCatcher1 天前
Vue3导航菜单(Menu)
typescript·vue3·less
theMuseCatcher2 天前
Vue3评论(Comment)
typescript·vue3
afumu2 天前
把五个网页版 AI 拉进同一个群聊:不用 API key 的多 Agent 编排
人工智能·chrome·typescript
孟陬4 天前
Foobar 技术周刊#160:大模型让大规模形式化软件验证成为现实丨AI写C++代码之后会发生什么?丨我们真的需要alpha() 函数吗丨重试,有时会让故障更
前端·后端·typescript
螺丝钉tina5 天前
[Playwright ][16]Playwright + TypeScript API 自动化测试实战:API测试
前端·javascript·typescript
华玥作者5 天前
Vue 3 + TypeScript + uni-app 组件库推荐:hy-app(华玥组件库)
vue.js·typescript·uni-app
Momo__6 天前
你写的 import 重试,从来没生效过
前端·javascript·typescript
长不大的杨瑞杰7 天前
OpenCode v2 Custom Tools 实战:开发数据库、工单与发布工具
人工智能·typescript·开发工具·opencode·custom tools
shmily麻瓜小菜鸡7 天前
TypeScript 知识点补充(第三部分:工程化与高级类型)
前端·javascript·typescript
腾科IT教育7 天前
TypeScript 泛型(Generics):类型占位符实现复用与安全
安全·typescript·泛型