wenminjie
2026-07-17 cd44290dc230d64ef9e382777b9722e81a661570
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
53
54
55
56
57
58
const http = require("http");
const fs = require("fs");
const path = require("path");
const url = require("url");
 
const root = __dirname;
const startPort = Number(process.env.PORT || 5173);
const mimeTypes = {
  ".html": "text/html; charset=utf-8",
  ".css": "text/css; charset=utf-8",
  ".js": "application/javascript; charset=utf-8",
  ".svg": "image/svg+xml; charset=utf-8",
  ".json": "application/json; charset=utf-8"
};
 
function createServer(port) {
  const server = http.createServer((request, response) => {
    const parsed = url.parse(request.url);
    const pathname = decodeURIComponent(parsed.pathname === "/" ? "/index.html" : parsed.pathname);
    let filePath = path.resolve(root, "." + pathname);
 
    if (!filePath.startsWith(root)) {
      response.writeHead(403);
      response.end("Forbidden");
      return;
    }
 
    if (!fs.existsSync(filePath) && pathname.endsWith(".html") && pathname !== "/index.html") {
      filePath = path.resolve(root, "./pages" + pathname);
    }
 
    fs.readFile(filePath, (error, content) => {
      if (error) {
        response.writeHead(404);
        response.end("Not found");
        return;
      }
      response.writeHead(200, {
        "Content-Type": mimeTypes[path.extname(filePath)] || "application/octet-stream"
      });
      response.end(content);
    });
  });
 
  server.on("error", (error) => {
    if (error.code === "EADDRINUSE" && port < startPort + 20) {
      createServer(port + 1);
      return;
    }
    throw error;
  });
 
  server.listen(port, () => {
    console.log("visitor-admin-ui running at http://localhost:" + port + "/");
  });
}
 
createServer(startPort);