10. 静态文件服务器
例子:
(1)创建http服务
(2)访问拼接文件
(3)规范url
(4)获取文件的后缀,设置不同的content-type
(5)404页面
(6)处理请求的url只保留路径和文件,去掉url后缀
// 导入模块
const http = require('http');
const fs = require('fs');
const url = require('url');
const path = require('path');
// 1.创建http服务
http.createServer(function (req,res) {
// console.log(req.url);
// 处理请求的url只保留路径和文件,去掉url访问的后缀
let pathname = url.parse(req.url).pathname;
console.log(pathname);
// 6.把index.html设置为每个目录默认打开的文件
if(pathname.indexOf('.') === -1){
pathname = path.join(pathname,'index.html')
}
console.log(pathname);
// 2.访问目录前加上htdocs文件夹,拼接文件名
// 3.path.normalize()规范url,以防恶意多字符htdocs//////zhang
let fileurl = path.normalize(path.join('../htdocs',pathname));
console.log(fileurl);//htdocs\zhang
//4. 获取文件的后缀,设置不同的content-type
let extname = path.extname(fileurl);
console.log(extname);
// 5.如果访问的文件不存在,加载404页面
// 读取文件
fs.readFile(fileurl,function (err,data) {
if(err){
fs.readFile('../htdocs/404.html',function (err,data) {
if (err) throw err;
res.writeHead(404,{'Content-type':'text/html;charset=utf8'});
res.end(data);
})
return;
}
//根据不同的文件后缀设置不同的content-type
// switch (extname){
// case '.html':contentType = 'text/html;charset=utf8';
// case '.css'.....
// }
// 以上判断文件后缀,设置格式,由于太多,所以引入json文件
// 读取mime.json
fs.readFile('mime.json',function (err,mimeData) {
if (err) throw err;
console.log(JSON.parse(mimeData));
let mimeList = JSON.parse(mimeData);//处理json数据
let contentType = mimeList[extname] || 'text/plain';//根据扩展名获取contentType
// 设置响应头
res.writeHead(200,{'Content-type':contentType});
// 结束响应
res.end(data);
});
});
}).listen(8002,function () {
console.log('http server is runing on port 8002');
});