const http = require('http');
const fs = require('fs');
const path = require('path');
const port = 3000;
const directory = 'web/';
const server = http.createServer((req, res) => {
// 获取请求的 URL 路径
const urlPath = req.url;
// 设置默认首页为 index.html
const filePath = directory + (urlPath === '/' ? 'index.html' : urlPath);
// 构建文件路径
const fullPath = path.join(__dirname, filePath);
// 读取文件内容并返回
fs.readFile(fullPath, (err, data) => {
if (err) {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end('File not found');
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data);
}
});
});
server.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
本地nodejs启动web服务
最新推荐文章于 2024-07-24 23:00:08 发布