运行时包管理器打包器测试运行器代码检查格式化指南参考博客反馈

将文件作为 HTTP 响应流式传输

Bun.file() 接受一个路径,并返回一个延迟加载的 BunFile 实例,你可以将其直接传递给 new Response 构造函数。

server.ts
const path = "/path/to/file.txt";
const file = Bun.file(path);
const resp = new Response(file);

Bun 根据文件扩展名确定 Content-Type,并将其设置在 Response 上。

server.ts
new Response(Bun.file("./package.json")).headers.get("Content-Type");
// => application/json;charset=utf-8

new Response(Bun.file("./test.txt")).headers.get("Content-Type");
// => text/plain;charset=utf-8

new Response(Bun.file("./index.tsx")).headers.get("Content-Type");
// => text/javascript;charset=utf-8

new Response(Bun.file("./img.png")).headers.get("Content-Type");
// => image/png

结合 Bun.serve() 一起使用。

server.ts
// 静态文件服务器
Bun.serve({
  async fetch(req) {
    const path = new URL(req.url).pathname;
    const file = Bun.file(path);
    return new Response(file);
  },
});

请参阅 Bun.write()。