const http = require('http'); //导入系统模块http
const url = require('url'); //导入系统模块rul
const path = require('path'); //导入系统模块path
const fs = require('fs'); //导入系统模块fs
const mime = require('mime') //引入第三方模块mime
const app = http.createServer(); //创建网站服务器
app.on('request', (req,res) => {
let pathname = url.parse(req.url).pathname; //获取用户的请求路径
pathname = pathname == '/' ? '/default.html' : pathname;
//将用户的请求路径转换为服务器硬盘路径
let realPath = path.join(__dirname , 'public' + pathname);
let type = mime.getType(realPath); //获取文件类型
//读取文件
fs.readFile(realPath,(err,res)=>{
//如果文件读取失败
if (err != null) {
res.writeHead(404,{
'content-type': 'text/html;charset=utf8' //避免乱码
})
res.end('文件读取失败');
return;
}
res.writeHead(200,{
'content-type': type //指定返回的文件类型,避免旧版浏览器出现问题
})
res.end(res); //把文件读取的结果响应给客户端
});
});
app.listen(3000); //监听端口
console.log('服务器启动成功');