Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
133 lines (123 loc) · 4.98 KB
/
Copy pathserver.js
File metadata and controls
133 lines (123 loc) · 4.98 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#!/usr/bin/env node
/**
* 备考笔记本地浏览服务(零依赖,npm start 即用)
*
* 用法:
* npm start # 默认端口 4545,被占用自动 +1,并尝试打开浏览器
* PORT=9000 npm start # 指定端口
* npm start -- --no-open # 不自动打开浏览器
*/
const http = require('http');
const fs = require('fs');
const path = require('path');
const { spawn } = require('child_process');
const ROOT = path.join(__dirname, 'notes');
const NO_OPEN = process.argv.includes('--no-open') || process.env.NO_OPEN === '1';
let BASE_PORT = Number(process.env.PORT) || 4545;
const MIME = {
'.html': 'text/html; charset=utf-8',
'.htm': 'text/html; charset=utf-8',
'.md': 'text/plain; charset=utf-8',
'.txt': 'text/plain; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.webp': 'image/webp',
'.ico': 'image/x-icon',
'.pdf': 'application/pdf',
'.woff2': 'font/woff2',
};
function send(res, code, body, type) {
res.writeHead(code, {
'Content-Type': type || 'text/html; charset=utf-8',
'Cache-Control': 'no-cache',
});
res.end(body);
}
function page(title, body) {
return `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1"><title>${title}</title>
<style>body{font-family:-apple-system,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;
background:#F7F8FF;color:#1F2433;display:flex;min-height:100vh;align-items:center;justify-content:center;margin:0}
.box{background:#fff;border:1px solid #E7EAF5;border-radius:16px;padding:36px 44px;max-width:520px;
box-shadow:0 8px 24px rgba(31,36,51,.06)}h1{margin:0 0 10px;font-size:22px}p{margin:6px 0;color:#4A5168;line-height:1.7}
a{color:#5B6CFF}</style></head><body><div class="box">${body}</div></body></html>`;
}
const server = http.createServer((req, res) => {
// 兼容浏览器百分号编码与命令行裸 UTF-8 两种路径
const raw = (req.url || '/').split('?')[0];
let pathname;
try {
pathname = decodeURIComponent(raw);
} catch {
pathname = raw;
}
if (pathname.endsWith('/')) pathname += 'index.html';
const filePath = path.normalize(path.join(ROOT, pathname));
if (filePath !== ROOT && !filePath.startsWith(ROOT + path.sep)) {
return send(res, 403, page('403', '<h1>403 Forbidden</h1><p>只能访问 notes/ 目录内的文件。</p>'));
}
fs.stat(filePath, (err, st) => {
if (!err && st.isDirectory()) {
res.writeHead(301, { Location: encodeURI(pathname.replace(/index\.html$/, '')) });
return res.end();
}
if (err || !st.isFile()) {
return send(res, 404, page('404 笔记不存在',
`<h1>404 · 这个页面不存在</h1><p><code>${pathname}</code></p>
<p>去 <a href="/">笔记总索引</a> 找找吧。</p>`));
}
const type = MIME[path.extname(filePath).toLowerCase()] || 'application/octet-stream';
res.writeHead(200, { 'Content-Type': type, 'Cache-Control': 'no-cache' });
fs.createReadStream(filePath).pipe(res);
});
});
function openBrowser(url) {
if (NO_OPEN) return;
let cmd, args;
const wsl = /microsoft/i.test(fs.readFileSync('/proc/version', 'utf8').toString());
if (wsl) {
cmd = 'cmd.exe'; args = ['/c', 'start', '', url]; // WSL2 调 Windows 默认浏览器
} else if (process.platform === 'darwin') {
cmd = 'open'; args = [url];
} else {
cmd = 'xdg-open'; args = [url];
}
try {
spawn(cmd, args, { stdio: 'ignore', detached: true }).on('error', () => {});
} catch { /* 打不开就算了,手动访问即可 */ }
}
function listen(port, tries) {
server.once('error', (e) => {
if (e.code === 'EADDRINUSE' && tries > 0) {
console.log(`端口 ${port} 被占用,改用 ${port + 1} …`);
listen(port + 1, tries - 1);
} else {
console.error('启动失败:', e.message);
process.exit(1);
}
});
server.listen(port, '127.0.0.1', () => {
const url = `http://localhost:${port}`;
console.log('');
console.log(' 📚 系统集成项目管理工程师 · 备考笔记服务已启动');
console.log(` ─────────────────────────────────────────`);
console.log(` 总索引 ${url}/`);
console.log(` 45 天计划 ${url}/备考重点规划_45天.html`);
console.log(` 公式卡 ${url}/计算公式速查卡.html`);
console.log(' ─────────────────────────────────────────');
console.log(' 停止服务:Ctrl + C');
console.log('');
openBrowser(url);
});
}
if (!fs.existsSync(path.join(ROOT, 'index.html'))) {
console.error('未找到 notes/index.html,请先运行 python3 notes/_txt/make_index.py 生成索引页。');
process.exit(1);
}
listen(BASE_PORT, 10);