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 > File I/O 를 참조하세요.

Bun by www.bunjs.com.cn 편집