Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
78 lines (70 loc) · 2.14 KB
/
Copy pathserver.js
File metadata and controls
78 lines (70 loc) · 2.14 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
const http = require("http");
const fs = require("fs");
const path = require("path");
const repoRoot = __dirname;
const port = Number(process.env.PORT || 8080);
const contentTypes = {
".html": "text/html; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".mjs": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".json": "application/json; charset=utf-8",
".wasm": "application/wasm",
".map": "application/json; charset=utf-8",
};
function resolveRequestPath(urlPath) {
let relativePath;
if (urlPath === "/") {
relativePath = "examples/threejs-demo/index.html";
// relativePath = "dist/index.html";
} else {
relativePath = decodeURIComponent(urlPath.slice(1));
if (relativePath.endsWith("/")) {
relativePath += "index.html";
}
}
const absolutePath = path.normalize(path.join(repoRoot, relativePath));
if (!absolutePath.startsWith(repoRoot)) {
return null;
}
return absolutePath;
}
const server = http.createServer((req, res) => {
const absolutePath = resolveRequestPath(req.url || "/");
if (!absolutePath) {
res.writeHead(400, { "Content-Type": "text/plain; charset=utf-8" });
res.end("Bad request");
return;
}
fs.readFile(absolutePath, (err, data) => {
if (err) {
res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
res.end(`Not found: ${path.relative(repoRoot, absolutePath)}`);
return;
}
const ext = path.extname(absolutePath);
res.writeHead(200, {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "*",
"Cache-Control": "no-cache",
"Content-Type": contentTypes[ext] || "application/octet-stream",
});
res.end(data);
});
});
function startServer(currentPort) {
server
.once("error", (err) => {
if (err.code === "EADDRINUSE") {
const nextPort = currentPort + 1;
startServer(nextPort);
return;
}
throw err;
})
.listen(currentPort, () => {
console.log(`server start at http://localhost:${currentPort}`);
console.log("default demo:", `http://localhost:${currentPort}/dist/`);
});
}
startServer(port);