aboutsummaryrefslogtreecommitdiff
path: root/docs/guides/http/stream-file.md
diff options
context:
space:
mode:
authorGravatar Colin McDonnell <colinmcd94@gmail.com> 2023-07-26 14:59:39 -0700
committerGravatar GitHub <noreply@github.com> 2023-07-26 14:59:39 -0700
commit4c89c60867591b50e0b31bf5009fd5ad6a3cebe1 (patch)
treefc1d2f47309c0345a850933496baa40d94bfdcbb /docs/guides/http/stream-file.md
parent6bfee02301a2e2a0b79339974af0445eb5a2688f (diff)
downloadbun-4c89c60867591b50e0b31bf5009fd5ad6a3cebe1.tar.gz
bun-4c89c60867591b50e0b31bf5009fd5ad6a3cebe1.tar.zst
bun-4c89c60867591b50e0b31bf5009fd5ad6a3cebe1.zip
Add files (#3826)
Diffstat (limited to 'docs/guides/http/stream-file.md')
-rw-r--r--docs/guides/http/stream-file.md48
1 files changed, 48 insertions, 0 deletions
diff --git a/docs/guides/http/stream-file.md b/docs/guides/http/stream-file.md
new file mode 100644
index 000000000..66c8c247b
--- /dev/null
+++ b/docs/guides/http/stream-file.md
@@ -0,0 +1,48 @@
+---
+name: Stream a file as an HTTP Response
+---
+
+This snippet reads a file from disk using [`Bun.file()`](/docs/api/file-io#reading-files-bun-file). This returns a `BunFile` instance, which can be passed directly into the `new Response` constructor.
+
+```ts
+const path = "/path/to/file.txt";
+const file = Bun.file(path);
+const resp = new Response(file);
+```
+
+---
+
+The `Content-Type` is read from the file and automatically set on the `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
+```
+
+---
+
+Putting it all together with [`Bun.serve()`](/docs/api/http#serving-files-bun-serve).
+
+```ts
+// static file server
+Bun.serve({
+ async fetch(req) {
+ const path = new URL(req.url).pathname;
+ const file = Bun.file(path);
+ return new Response(file);
+ },
+});
+```
+
+---
+
+See [Docs > API > File I/O](/docs/api/file-io#writing-files-bun-write) for complete documentation of `Bun.write()`.