39 lines
1.4 KiB
JavaScript
39 lines
1.4 KiB
JavaScript
import { createReadStream, existsSync, statSync } from "node:fs";
|
|
import { createServer } from "node:http";
|
|
import { extname, join, normalize } from "node:path";
|
|
|
|
const root = process.cwd();
|
|
const port = Number(process.env.PORT || 4173);
|
|
|
|
const mimeTypes = {
|
|
".css": "text/css; charset=utf-8",
|
|
".html": "text/html; charset=utf-8",
|
|
".js": "text/javascript; charset=utf-8",
|
|
".jpg": "image/jpeg",
|
|
".jpeg": "image/jpeg",
|
|
".png": "image/png",
|
|
".svg": "image/svg+xml",
|
|
};
|
|
|
|
createServer((request, response) => {
|
|
const pathname = decodeURIComponent(new URL(request.url, `http://${request.headers.host}`).pathname);
|
|
const requested = pathname === "/" ? "/index.html" : pathname;
|
|
const safePath = normalize(requested).replace(/^(\.\.(\/|\\|$))+/, "");
|
|
let filePath = join(root, safePath);
|
|
|
|
if (!filePath.startsWith(root) || !existsSync(filePath)) {
|
|
response.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
|
|
response.end("Nicht gefunden");
|
|
return;
|
|
}
|
|
|
|
if (statSync(filePath).isDirectory()) filePath = join(filePath, "index.html");
|
|
response.writeHead(200, {
|
|
"Content-Type": mimeTypes[extname(filePath).toLowerCase()] || "application/octet-stream",
|
|
"Cache-Control": "no-cache",
|
|
});
|
|
createReadStream(filePath).pipe(response);
|
|
}).listen(port, "127.0.0.1", () => {
|
|
console.log(`Hardtschule-Website: http://127.0.0.1:${port}`);
|
|
});
|