-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.mjs
More file actions
49 lines (44 loc) · 1.58 KB
/
Copy pathserver.mjs
File metadata and controls
49 lines (44 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import { createServer } from "node:http";
import { readFile, stat } from "node:fs/promises";
import { extname, join, normalize } from "node:path";
import { fileURLToPath } from "node:url";
const root = fileURLToPath(new URL("./", import.meta.url));
const port = Number(process.env.PORT || 4173);
const types = {
".html": "text/html; charset=utf-8",
".css": "text/css; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".mjs": "text/javascript; charset=utf-8",
".json": "application/json; charset=utf-8",
".md": "text/markdown; charset=utf-8",
".svg": "image/svg+xml"
};
function safePath(urlPath) {
const decoded = decodeURIComponent(urlPath.split("?")[0]);
const relative = normalize(decoded).replace(/^([/\\])+/, "");
const candidate = join(root, relative || "index.html");
return candidate.startsWith(root) ? candidate : null;
}
const server = createServer(async (request, response) => {
let path = safePath(request.url || "/");
if (!path) {
response.writeHead(403).end("Forbidden");
return;
}
try {
if ((await stat(path)).isDirectory()) path = join(path, "index.html");
const body = await readFile(path);
response.writeHead(200, {
"Content-Type": types[extname(path)] || "application/octet-stream",
"Cache-Control": "no-store",
"X-Content-Type-Options": "nosniff"
});
response.end(body);
} catch {
response.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
response.end("Not found");
}
});
server.listen(port, "127.0.0.1", () => {
console.log(`Before the Component: http://127.0.0.1:${port}`);
});