Skip to content

Static File Server

Serve static files from a mounted directory, useful for hosting a website or a single-page app.

src/index.ts
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;

Mount a directory containing your static files into the sandbox.

kyushu.run.toml
[[mounts]]
host = "./dist"
guest = "/"

Try it

Build and run the worker with its config.

Terminal window
kyu build && kyu run kyushu.run.toml

Then send a request to test it.

Terminal window
curl http://localhost:5987

Or open your browser at http://localhost:5987.