const http = require('http');
const fs = require('fs');
const path = require('path');
const server = http.createServer((req, res) => {
// 处理首页请求
if (req.url === '/') {
fs.readFile(path.join(__dirname, 'index.html'), (err, data) => {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
} else {
// 处理其他静态文件请求
const filePath = path.join(__dirname, req.url);
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(404);
return res.end('404 not found');
}
res.writeHead(200);
res.end(data);
});
}
});
const port = process.env.PORT || 3000;
server.listen(port, () => console.log(`Server running at http://localhost:${port}`));
nodejs 静态服务
最新推荐文章于 2025-03-12 08:22:00 发布