47 lines
1.6 KiB
JavaScript
47 lines
1.6 KiB
JavaScript
import { createReadStream } from "node:fs";
|
|
import { stat } from "node:fs/promises";
|
|
import { createServer } from "node:http";
|
|
import { extname, resolve, sep } from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
|
|
const root = resolve(fileURLToPath(new URL("../..", import.meta.url)));
|
|
const host = "127.0.0.1";
|
|
const port = Number.parseInt(process.env.FROST_TEST_PORT ?? "4173", 10);
|
|
const contentTypes = new Map([
|
|
[".css", "text/css; charset=utf-8"],
|
|
[".html", "text/html; charset=utf-8"],
|
|
[".js", "text/javascript; charset=utf-8"],
|
|
[".mjs", "text/javascript; charset=utf-8"],
|
|
[".png", "image/png"],
|
|
[".svg", "image/svg+xml"],
|
|
]);
|
|
|
|
const server = createServer(async (request, response) => {
|
|
try {
|
|
const url = new URL(request.url ?? "/", `http://${host}:${port}`);
|
|
const pathname = decodeURIComponent(url.pathname === "/" ? "/examples/index.html" : url.pathname);
|
|
const file = resolve(root, `.${pathname}`);
|
|
|
|
if (file !== root && !file.startsWith(`${root}${sep}`)) {
|
|
response.writeHead(403).end("Forbidden");
|
|
return;
|
|
}
|
|
|
|
const metadata = await stat(file);
|
|
if (!metadata.isFile()) throw new Error("Not a file");
|
|
|
|
response.writeHead(200, {
|
|
"Cache-Control": "no-store",
|
|
"Content-Type": contentTypes.get(extname(file)) ?? "application/octet-stream",
|
|
});
|
|
createReadStream(file).pipe(response);
|
|
} catch {
|
|
response.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" }).end("Not found");
|
|
}
|
|
});
|
|
|
|
server.listen(port, host, () => {
|
|
console.log(`Frost example server listening on http://${host}:${port}`);
|
|
});
|
|
|