Skip to content

此代碼片段使用 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

Bun學習網由www.bunjs.com.cn整理維護