此代码片段使用 Bun.file() 从磁盘读取文件。这返回一个 BunFile 实例,可以直接传递给 new Response 构造函数。
ts
const path = "/path/to/file.txt";
const file = Bun.file(path);
const resp = new Response(file);Content-Type 从文件中读取并自动设置在 Response 上。
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() 一起使用。
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。