// 简易静态服务器,根目录为 军政门户/ // 用法: node server.js [port] const http = require('http'); const fs = require('fs'); const path = require('path'); const ROOT = path.resolve(__dirname); const PORT = process.argv[2] || 8765; const MIME = { '.html': 'text/html; charset=utf-8', '.css': 'text/css; charset=utf-8', '.js': 'application/javascript; charset=utf-8', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.gif': 'image/gif', '.ico': 'image/x-icon', '.svg': 'image/svg+xml' }; const server = http.createServer((req, res) => { let url = decodeURIComponent(req.url.split('?')[0]); if (url === '/') url = '/css/首页模板.html'; const filePath = path.join(ROOT, url); // 防越界 if (!filePath.startsWith(ROOT)) { res.writeHead(403); return res.end('Forbidden'); } fs.stat(filePath, (err, stat) => { if (err || !stat.isFile()) { res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' }); return res.end('404 Not Found: ' + url); } const ext = path.extname(filePath).toLowerCase(); res.writeHead(200, { 'Content-Type': MIME[ext] || 'application/octet-stream' }); fs.createReadStream(filePath).pipe(res); }); }); server.listen(PORT, '127.0.0.1', () => { console.log(`预览服务器已启动: http://localhost:${PORT}/`); console.log(`首页模板: http://localhost:${PORT}/preview.html`); });