Static File Server
Serve static files from a mounted directory, useful for hosting a website or a single-page app.
import type { ExportedHandler } from "kyushu-types";import { readFile, access } from "node:fs/promises";import { join } from "node:path";import mime from "mime-types";
export default { async fetch({ url: requestUrl }) { const url = URL.parse(requestUrl);
if (url === null) { return { status: 400, body: "Bad Request" }; }
const { pathname } = url;
const sanitizedPathname = pathname === "/" ? "/index.html" : pathname; const filepath = join(process.cwd(), "public", sanitizedPathname);
try { await access(filepath); } catch { return { status: 404, body: "Not Found" }; }
try { const file = await readFile(filepath); const mimeType = mime.lookup(filepath);
return { status: 200, headers: { "content-type": typeof mimeType === "string" ? mimeType : "application/octet-stream", }, body: file, }; } catch { return { status: 500, body: "Internal Server Error" }; } },} satisfies ExportedHandler;Config
Section titled “Config”Mount a directory containing your static files into the sandbox.
[[mounts]]host = "./dist"guest = "/"Try it
Build and run the worker with its config.
kyu build && kyu run kyushu.run.tomlThen send a request to test it.
curl http://localhost:5987Or open your browser at http://localhost:5987.