mime.json文件
链接:https://pan.baidu.com/s/1zDtI4lALn8zCI2OIIGoB1Q
提取码:94xi
复制这段内容后打开百度网盘手机App,操作更方便哦
步骤一:先把上述json文件下载下来。
作用:将Content-Type封装,方便响应头调用。
代码
创建一个StaticServer.js文件,通过require导入path,fs模块,以及将上面下载好的mime.json文件以模块形式导入。最终通过exports将方法暴露出去。
let path = require("path");
let fs = require("fs");
let mime = require("./mime.json");
function readFile(req,res,rootPath) {
let filePath = path.join(rootPath,req.url);
// console.log(filePath);
let extName = path.extname(filePath);
// console.log(ext);
let type = mime[extName];
// console.log(type);
if(type){
if(type.startsWith('text')){
type += "; charset=utf-8;";
}
res.writeHead(200,{"Content-Type": type});
fs.readFile(filePath,f