import http from 'http'; import fs from 'fs'; import path from 'path'; import { networkInterfaces } from 'os'; const PORT = process.env.PORT || 8765; const HOST = '0.0.0.0'; const mimeTypes = { '.html': 'text/html', '.js': 'application/javascript', '.json': 'application/json', '.css': 'text/css', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.mp3': 'audio/mpeg', }; function getLocalIPs() { const nets = networkInterfaces(); const ips = []; for (const name of Object.keys(nets)) { for (const net of nets[name]) { if (net.family === 'IPv4' && !net.internal) { ips.push(net.address); } } } return ips; } const server = http.createServer((req, res) => { let filePath = '.' + (req.url === '/' ? '/index.html' : req.url); const ext = path.extname(filePath).toLowerCase(); const contentType = mimeTypes[ext] || 'application/octet-stream'; fs.readFile(filePath, (err, content) => { if (err) { res.writeHead(404); res.end('Not found'); return; } res.writeHead(200, { 'Content-Type': contentType }); res.end(content); }); }); server.listen(PORT, HOST, () => { console.log(`\n 轮回录 服务器已启动`); console.log(` ========================`); console.log(` 本机访问: http://localhost:${PORT}`); const ips = getLocalIPs(); for (const ip of ips) { console.log(` 局域网访问: http://${ip}:${PORT}`); } console.log(` ========================\n`); });