核心工具链运行时
运行时
运行 TypeScript、执行脚本、读取环境变量并启动 HTTP 服务
最后更新于
什么时候用
当目标是执行 JavaScript / TypeScript,而不是安装依赖、跑测试或生成 bundle 时,使用 Bun 运行时。
bun run index.ts
bun index.ts # 等价的简写
bun run dev # package.json 脚本
bun --watch index.ts # 文件变化后重启
bun --hot index.ts # 尝试保留进程状态的热重载TypeScript 与模块
Bun 原生解析 .ts、.tsx、JSX 和 ESM/CommonJS 常见形式。它执行 TypeScript 时会剥离类型;静态检查仍交给 TypeScript:
bun add -d typescript
bunx tsc --noEmit环境变量
Bun 会自动读取常见 .env 文件。代码中可使用 process.env 或 Bun.env:
const port = Number(Bun.env.PORT ?? 3000);
const apiKey = Bun.env.API_KEY;
if (!apiKey) throw new Error('API_KEY is required');边界
不要把密钥写进源码、日志或交给不受信任的 Agent。浏览器 bundle 中也不得读取服务端密钥。
HTTP 服务
const server = Bun.serve({
port: Number(Bun.env.PORT ?? 3000),
routes: {
'/health': () => Response.json({ ok: true }),
'/users/:id': (req) => Response.json({ id: req.params.id }),
},
fetch() {
return new Response('Not found', { status: 404 });
},
});
console.log(server.url.href);常用运行时 API
| 目标 | API | 备注 |
|---|---|---|
| 读写文件 | Bun.file() / Bun.write() | Bun.file() 返回惰性 Blob 风格对象 |
| HTTP 服务 | Bun.serve() | 基于标准 Request / Response |
| 子进程 | Bun.spawn() / Bun.spawnSync() | 参数使用数组可减少 shell 注入风险 |
| 哈希 | Bun.hash() / Bun.password | 密码请使用专门的 Bun.password |
| SQLite | bun:sqlite | 内置驱动,仍需设计迁移与连接生命周期 |
| SQL | Bun.SQL | PostgreSQL、MySQL、SQLite;需要连接池预算和迁移流程 |
| Redis | RedisClient | 当前要求 Redis 7.2+;显式关闭长连接 |
| 对象存储 | S3Client | 支持 S3-compatible 服务,权限仍由服务端控制 |
| Shell | Bun.$ | 只使用可信命令结构;不把未验证输入拼进 shell |
数据库、缓存和对象存储的完整边界见 数据库与存储。
优雅退出
const server = Bun.serve({ fetch: () => new Response('ok') });
async function shutdown() {
await server.stop();
process.exit(0);
}
process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);生产服务还应等待数据库、队列等资源关闭,并设置超时兜底。
云环境边界
Bun.serve会读取PORT,也可显式传入port;容器平台注入端口时不要硬编码。- 默认监听所有接口,生产环境应由平台网络策略、反向代理和鉴权共同控制访问。
- 默认空闲超时是 10 秒。AI 流式响应或长请求需要评估
idleTimeout,必要时对单个请求使用server.timeout(request, 0);同时保留应用级总超时和取消机制。 - 使用
maxRequestBodySize限制请求体,上传文件不要无限缓冲到内存。
官方参考:Runtime、HTTP server、Bun APIs。