將檔案作為 HTTP 響應流式傳輸
Bun.file() 接受一個路徑,並傳回一個延遲載入的 BunFile 例項,你可以將其直接傳遞給 new Response 建構函式。
const path = "/path/to/file.txt";
const file = Bun.file(path);
const resp = new Response(file);
Bun 根據副檔名確定 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()。