-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
81 lines (71 loc) · 2.08 KB
/
Copy pathserver.js
File metadata and controls
81 lines (71 loc) · 2.08 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
79
80
81
/**
* NetLearner 开发服务器
*
* 职责:
* 1. 提供静态文件服务
* 2. 强制所有响应禁用浏览器缓存
* 3. 零外部依赖,仅用 Node.js 内建模块
*
* 启动方式(唯一):
* node server.js
*/
const http = require('http');
const fs = require('fs');
const path = require('path');
const PORT = 8080;
const ROOT = __dirname;
const MIME_TYPES = {
'.html': 'text/html; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.js': 'application/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.ico': 'image/x-icon',
};
function serveFile(res, filePath) {
const ext = path.extname(filePath).toLowerCase();
const contentType = MIME_TYPES[ext] || 'application/octet-stream';
try {
const content = fs.readFileSync(filePath);
res.writeHead(200, {
'Content-Type': contentType,
'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate',
'Pragma': 'no-cache',
'Expires': '0',
'Surrogate-Control': 'no-store',
});
res.end(content);
} catch (err) {
if (err.code === 'ENOENT') {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('404 Not Found');
} else {
res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('500 Internal Server Error');
}
}
}
const server = http.createServer((req, res) => {
const urlPath = req.url.split('?')[0].split('#')[0];
let filePath = path.join(ROOT, urlPath === '/' ? 'index.html' : urlPath);
// Security: prevent directory traversal
if (!filePath.startsWith(ROOT)) {
res.writeHead(403);
res.end('Forbidden');
return;
}
try {
if (fs.existsSync(filePath) && fs.statSync(filePath).isDirectory()) {
filePath = path.join(filePath, 'index.html');
}
} catch (_) {
serveFile(res, filePath);
return;
}
serveFile(res, filePath);
});
server.listen(PORT, () => {
console.log(`NetLearner → http://localhost:${PORT}`);
console.log('Cache: DISABLED (all browsers)');
});