Files
flux-web/server.js
2026-01-22 18:31:30 +08:00

47 lines
1.4 KiB
JavaScript

const http = require('http');
const fs = require('fs');
const path = require('path');
const port = 3000;
const rootDir = __dirname;
const mimeTypes = {
'.html': 'text/html',
'.css': 'text/css',
'.js': 'application/javascript',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon'
};
const server = http.createServer((req, res) => {
let filePath = path.join(rootDir, req.url === '/' ? 'index.html' : req.url);
const extname = String(path.extname(filePath)).toLowerCase();
const contentType = mimeTypes[extname] || 'application/octet-stream';
fs.readFile(filePath, (error, content) => {
if (error) {
if (error.code === 'ENOENT') {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end('<h1>404 Not Found</h1>', 'utf-8');
} else {
res.writeHead(500);
res.end(`Server Error: ${error.code}`, 'utf-8');
}
} else {
res.writeHead(200, { 'Content-Type': contentType });
res.end(content, 'utf-8');
}
});
});
server.listen(port, () => {
console.log(`服务器已启动!`);
console.log(`访问地址: http://localhost:${port}`);
console.log(`按 Ctrl+C 停止服务器`);
});