web开发概述(05):静态资源服务
静态资源服务
/*
封装
ss.js
*/
const path = require('path');
const fs = require('fs');
const mime = require('./mime.json');
exports.staticServer = (req,res,root)=>{
fs.readFile(path.join(root,req.url),(err,fileContent)=>{
if(err){
//没有找到对应文件
res.writeHead(404,{
'Content-Type':'text/plain; charset=utf8'
});
res.end('页面无响应');
}else{
let dtype = 'text/html';
//获取请求文件的后缀
let ext = path.extname(req.url);
if(mime[ext]){
dtype = mime[ext];
}
//如果响应的内容为文本,就设置为utf8编码
if(dtype.startsWith('text')){
dtype += '; charset=utf8';
}
res.writeHead(200,{
'Content-type':dtype
});
res.end(fileContent);
}
});
}
测试
/*
测试
*/
const http = require('http');
const ss = require('./ss.js');
const path = require('path');
http.createServer((req, res) => {
ss.staticServer(req, res, path.join(__dirname, 'www'));
}).listen(3000, () => {
console.log('服务启动……');
});

浙公网安备 33010602011771号