前言
实现一个静态资源服务器,可以根据用户访问的不同路径显示不同的页面。
代码目录
/data/mime.json
/module/mime.js
let mimeMap = {};
const fs = require('fs');
exports.getMime = (extname)=>{
if(Object.keys(mimeMap).length === 0){
const data = fs.readFileSync("./data/mime.json");
const obj = JSON.parse(data.toString());
mimeMap = obj;
}
return mimeMap[extname] || mimeMap['.html'];
}
/static/ 文件夹下面没有什么好说的,就是一些静态的html页面。
/server.js
const http = require('http');
const path = require("path");
const url = require("url");
const fs = require("fs");
const listenPort = 8081; // 监听端口号
const mimeModule = require("./module/mime");
// 创建服务
http.createServer(function (request, response) {
let pathName = url.parse(request.url, true).pathname; // 获取pathname
if(pathName === '/favicon.ico') return;
if(pathName === '/') pathName = '/index.html';
const extName = path.extname(pathName); // 获取文件后缀
const mime = mimeModule.getMime(extName); // 获取对应的mime类型
response.writeHead(200, {'Content-Type': `${mime};chartset="utf-8"`}); // 设置响应头
fs.readFile(`./static/${pathName}`, (err, data)=>{
if(err){
fs.readFile(`./static/404.html`, (err2, data2)=>{
if(err2){
console.log(err2);
return;
}
response.write(data2); // 返回数据
response.end();
})
return;
}
response.write(data); // 返回数据
response.end();
})
}).listen(listenPort);
console.log(`Server running at http://127.0.0.1:${listenPort}`);