|
|
@@ -6,6 +6,11 @@ const cors = require('cors');
|
|
|
const app = express();
|
|
|
const PORT = 3000;
|
|
|
|
|
|
+// index.md 缓存
|
|
|
+let indexCache = null;
|
|
|
+let indexCacheTime = 0;
|
|
|
+const CACHE_DURATION = 5000; // 5秒缓存
|
|
|
+
|
|
|
// 路径安全验证函数 - 防止路径遍历攻击
|
|
|
function sanitizePath(input) {
|
|
|
if (!input || typeof input !== 'string') {
|
|
|
@@ -33,25 +38,24 @@ app.use(express.json({ limit: '10mb' })); // 增加请求体大小限制到10MB
|
|
|
app.use(express.urlencoded({ limit: '10mb', extended: true }));
|
|
|
app.use(express.static('public'));
|
|
|
|
|
|
-// API: 获取 index.md 内容
|
|
|
-app.get('/api/index', async (req, res) => {
|
|
|
- try {
|
|
|
- const indexPath = path.join(__dirname, 'docs', 'index.md');
|
|
|
- const content = await fs.readFile(indexPath, 'utf-8');
|
|
|
- res.json({ content });
|
|
|
- } catch (error) {
|
|
|
- res.status(500).json({ error: '无法读取 index.md', details: error.message });
|
|
|
+// 获取 index.md 结构(带缓存)
|
|
|
+async function getIndexStructure() {
|
|
|
+ const now = Date.now();
|
|
|
+ if (indexCache && (now - indexCacheTime < CACHE_DURATION)) {
|
|
|
+ return indexCache;
|
|
|
}
|
|
|
-});
|
|
|
+
|
|
|
+ const indexPath = path.join(__dirname, 'docs', 'index.md');
|
|
|
+ const content = await fs.readFile(indexPath, 'utf-8');
|
|
|
+ indexCache = parseIndexMd(content);
|
|
|
+ indexCacheTime = now;
|
|
|
+ return indexCache;
|
|
|
+}
|
|
|
|
|
|
// API: 解析 index.md 结构
|
|
|
app.get('/api/structure', async (req, res) => {
|
|
|
try {
|
|
|
- const indexPath = path.join(__dirname, 'docs', 'index.md');
|
|
|
- const content = await fs.readFile(indexPath, 'utf-8');
|
|
|
-
|
|
|
- // 解析结构
|
|
|
- const structure = parseIndexMd(content);
|
|
|
+ const structure = await getIndexStructure();
|
|
|
res.json(structure);
|
|
|
} catch (error) {
|
|
|
res.status(500).json({ error: '无法解析文档结构', details: error.message });
|
|
|
@@ -67,11 +71,7 @@ app.get('/api/category/:category', async (req, res) => {
|
|
|
return res.status(400).json({ error: '无效的分类名称' });
|
|
|
}
|
|
|
|
|
|
- const indexPath = path.join(__dirname, 'docs', 'index.md');
|
|
|
- const content = await fs.readFile(indexPath, 'utf-8');
|
|
|
-
|
|
|
- // 解析并获取指定分类的文档
|
|
|
- const structure = parseIndexMd(content);
|
|
|
+ const structure = await getIndexStructure();
|
|
|
const categoryData = structure.find(cat => cat.name === category);
|
|
|
|
|
|
if (!categoryData) {
|