Bun.file() 从磁盘读取文件。该方法返回一个 BunFile 实例,可以直接传入 new Response 构造函数。
Content-Type 会从文件中读取并自动设置到 Response 上。
结合
Bun.serve() 一起使用。
完整的
Bun.write() 文档请参见 文档 > API > 文件 I/O。Bun.file() 从磁盘读取文件。该方法返回一个 BunFile 实例,可以直接传入 new Response 构造函数。
const path = "/path/to/file.txt";
const file = Bun.file(path);
const resp = new Response(file);
Content-Type 会从文件中读取并自动设置到 Response 上。
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() 一起使用。
// 静态文件服务器
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。