-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserve.js
More file actions
34 lines (31 loc) · 1.21 KB
/
Copy pathserve.js
File metadata and controls
34 lines (31 loc) · 1.21 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
// 静态站点服务器:node serve.js [port]
const http = require('http');
const fs = require('fs');
const path = require('path');
const ROOT = path.resolve(__dirname, "public");
const PORT = Number(process.argv[2]) || 8765;
const MIME = {
".html": "text/html; charset=utf-8",
".css": "text/css; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".json": "application/json; charset=utf-8",
".png": "image/png",
".ico": "image/x-icon",
".svg": "image/svg+xml",
".jpg": "image/jpeg",
".txt": "text/plain; charset=utf-8",
};
http.createServer((req, res) => {
let p = decodeURIComponent((req.url || "/").split("?")[0]);
if (p === "/") p = "/index.html";
const file = path.normalize(path.join(ROOT, p));
if (!file.startsWith(ROOT)) { res.writeHead(403); res.end('Forbidden'); return; }
fs.readFile(file, (err, data) => {
if (err) { res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' }); res.end('404 Not Found'); return; }
const ext = path.extname(file).toLowerCase();
res.writeHead(200, { 'Content-Type': MIME[ext] || 'application/octet-stream' });
res.end(data);
});
}).listen(PORT, () => {
console.log("Atlas clone running: http://127.0.0.1:" + PORT + "/");
});