const http = require('http'); const fs = require('fs'); const path = require('path'); const PORT = 7358; 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', '.png': 'image/png', '.jpg': 'image/jpeg', '.svg': 'image/svg+xml', }; function getMimeType(filepath) { const ext = path.extname(filepath).toLowerCase(); return MIME_TYPES[ext] || 'application/octet-stream'; } function readMarkdownFile(filepath) { try { const content = fs.readFileSync(filepath, 'utf-8'); return { success: true, content: content, name: path.basename(filepath) }; } catch (error) { return { success: false, error: error.message }; } } function getDocsList() { const docsDir = path.join(__dirname, '../docs'); try { const files = fs.readdirSync(docsDir).filter(f => f.endsWith('.md')); return files.map(file => ({ name: file.replace('.md', ''), file: file, path: file.replace('.md', '') })); } catch (error) { return []; } } const server = http.createServer((req, res) => { // API: 获取文档列表 if (req.url === '/api/docs') { res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' }); res.end(JSON.stringify(getDocsList())); return; } // API: 获取单个文档 if (req.url.startsWith('/api/doc/')) { const docName = decodeURIComponent(req.url.substring(9)); const docPath = path.join(__dirname, '../docs', docName + '.md'); const result = readMarkdownFile(docPath); if (result.success) { res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' }); res.end(JSON.stringify(result)); } else { res.writeHead(404, { 'Content-Type': 'application/json; charset=utf-8' }); res.end(JSON.stringify({ success: false, error: 'Document not found' })); } return; } // 静态文件服务 let filepath = req.url === '/' ? '/index.html' : req.url; filepath = path.join(__dirname, filepath); if (fs.existsSync(filepath) && fs.statSync(filepath).isDirectory()) { filepath = path.join(filepath, 'index.html'); } if (fs.existsSync(filepath)) { const mimeType = getMimeType(filepath); res.writeHead(200, { 'Content-Type': mimeType }); fs.createReadStream(filepath).pipe(res); } else { res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' }); res.end('