Skip to main content
此示例使用 Bun.file() 从磁盘读取文件。该方法返回一个 BunFile 实例,可以直接传入 new Response 构造函数。
https://mintcdn.com/ikxin/42j8wRmGt8kDDLLK/icons/typescript.svg?fit=max&auto=format&n=42j8wRmGt8kDDLLK&q=85&s=a2a397cd68603d207db5c5b5d620260aserver.ts
const path = "/path/to/file.txt";
const file = Bun.file(path);
const resp = new Response(file);

Content-Type 会从文件中读取并自动设置到 Response 上。
https://mintcdn.com/ikxin/42j8wRmGt8kDDLLK/icons/typescript.svg?fit=max&auto=format&n=42j8wRmGt8kDDLLK&q=85&s=a2a397cd68603d207db5c5b5d620260aserver.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() 一起使用。
https://mintcdn.com/ikxin/42j8wRmGt8kDDLLK/icons/typescript.svg?fit=max&auto=format&n=42j8wRmGt8kDDLLK&q=85&s=a2a397cd68603d207db5c5b5d620260aserver.ts
// 静态文件服务器
Bun.serve({
  async fetch(req) {
    const path = new URL(req.url).pathname;
    const file = Bun.file(path);
    return new Response(file);
  },
});

完整的 Bun.write() 文档请参见 文档 > API > 文件 I/O