const http = require('http'); const fs = require('fs'); const path = require('path'); //mod:新增http服务,暂时未用到,代码暂留 class HttpServer { constructor() { this.server = null; } start() { const staticDir = path.join(__dirname, '../config'); // 从config文件中读取静态资源目录,默认为public目录 this.server = http.createServer((req, res) => { let filePath = path.join(staticDir, req.url === '/' ? 'index.html' : req.url); const extname = String(path.extname(filePath)).toLowerCase(); const mimeTypes = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpg', '.gif': 'image/gif', '.wav': 'audio/wav', '.mp4': 'video/mp4', '.woff': 'application/font-woff', '.ttf': 'application/font-ttf', '.eot': 'application/vnd.ms-fontobject', '.otf': 'application/font-otf', '.svg': 'application/image/svg+xml' }; const contentType = mimeTypes[extname] || 'application/octet-stream'; fs.readFile(filePath, (error, content) => { if (error) { if (error.code === 'ENOENT') { res.writeHead(404); res.end('404 Not Found'); } else { res.writeHead(500); res.end(`Server Error: ${error.code}`); } } else { res.writeHead(200, { 'Content-Type': contentType }); res.end(content, 'utf-8'); } }); }); const port = 7072; // 从config文件中读取端口号,默认为7072 this.server.listen(port, () => { console.log(`HTTP Server running at http://localhost:${port}/`); }); } stop() { if (this.server) { this.server.close(() => { console.log('HTTP Server closed'); }); } } } module.exports = HttpServer;