此代码段使用 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() 结合使用。
// static file server
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。