Files
anidev-design-system/scripts/serve.mjs
T

45 lines
1.4 KiB
JavaScript

import http from "node:http";
import { readFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import path from "node:path";
const root = path.resolve(fileURLToPath(new URL("../", import.meta.url)));
const types = {
".html": "text/html; charset=utf-8",
".css": "text/css; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".json": "application/json; charset=utf-8",
".svg": "image/svg+xml",
".md": "text/plain; charset=utf-8",
};
const port = Number(process.env.PORT || 4173);
http
.createServer(async (req, res) => {
try {
const pathname = decodeURIComponent(
new URL(req.url, "http://localhost").pathname,
);
if (pathname === "/") {
res.writeHead(302, { Location: "/playground/" });
res.end();
return;
}
const file = path.resolve(
root,
"." + (pathname.endsWith("/") ? pathname + "index.html" : pathname),
);
if (!file.startsWith(root + path.sep)) throw Error();
const data = await readFile(file);
res.writeHead(200, {
"Content-Type": types[path.extname(file)] || "application/octet-stream",
"Cache-Control": "no-store",
});
res.end(data);
} catch {
res.writeHead(404);
res.end("Not found");
}
})
.listen(port, "127.0.0.1", () =>
console.log(`Anidev Design System: http://127.0.0.1:${port}`),
);