Bun 1 运行时与服务端开发实践概述Bun 是现代 JavaScript/TypeScript 运行时,内置高性能 HTTP 服务器与工具链。本文通过 `Bun.serve` 与 Web 标准 `Request/Response` 示例,给出工程落地与性能优化要点。核心用法1. 启动 HTTP 服务// server.ts export const server = Bun.serve({ port: 3000, fetch(req) { const url = new URL(req.url) if (url.pathname === '/api/hello') { return Response.json({ message: 'Hello from Bun' }) } return new Response('OK', { headers: { 'content-type': 'text/plain' } }) }, }) console.log(`Listening on http://localhost:${server.port}`) 2. 静态文件与流式响应// static.ts const index = Bun.file('public/index.html') Bun.serve({ port: 3001, fetch(req) { const url = new URL(req.url) if (url.pathname === '/') return new Response(index) return new Response('Not Found', { status: 404 }) }, }) 性能与工程实践标准接口:统一使用 `Request/Response`,提升与边缘平台的适配性。资源复用:复用 `Bun.file` 与常用头部,减少重复构造与 GC 压力。生产参数:关闭调试日志,按需开启压缩与缓存头,降低带宽与 TTFB。验证要点示例基于稳定 API,可在本地直接运行;通过网络面板验证路由与静态资源行为。对比 Node 同构接口,确认迁移成本与性能收益(不使用未经验证的数字)。

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部
1.794784s