-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.mjs
More file actions
52 lines (47 loc) · 1.66 KB
/
Copy pathserver.mjs
File metadata and controls
52 lines (47 loc) · 1.66 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
50
51
52
import { createServer } from "node:http";
import { readFile, stat } from "node:fs/promises";
import { extname, join, normalize, resolve } from "node:path";
const root = resolve(".");
const port = Number(process.env.PORT || 4173);
const types = new Map([
[".html", "text/html; charset=utf-8"],
[".css", "text/css; charset=utf-8"],
[".js", "text/javascript; charset=utf-8"],
[".json", "application/json; charset=utf-8"],
[".pdf", "application/pdf"],
[".stl", "model/stl"],
[".obj", "text/plain; charset=utf-8"],
[".step", "text/plain; charset=utf-8"],
[".stp", "text/plain; charset=utf-8"]
]);
function safePath(urlPath) {
const decoded = decodeURIComponent(urlPath.split("?")[0]);
const target = normalize(join(root, decoded === "/" ? "index.html" : decoded));
if (!target.startsWith(root)) {
return null;
}
return target;
}
createServer(async (req, res) => {
try {
const target = safePath(req.url || "/");
if (!target) {
res.writeHead(403);
res.end("Forbidden");
return;
}
const info = await stat(target);
const file = info.isDirectory() ? join(target, "index.html") : target;
const body = await readFile(file);
res.writeHead(200, {
"content-type": types.get(extname(file).toLowerCase()) || "application/octet-stream",
"cache-control": "no-store"
});
res.end(body);
} catch (error) {
res.writeHead(error.code === "ENOENT" ? 404 : 500, { "content-type": "text/plain; charset=utf-8" });
res.end(error.code === "ENOENT" ? "Not found" : `Server error: ${error.message}`);
}
}).listen(port, () => {
console.log(`DfM Intelligence Assistant running at http://localhost:${port}`);
});