问题分析 : 由于一个html文件会引用多个静态资源,(.png,.css,.js)等,把所有的静态资源放在一个指定的目录里,,,收到用户的请求之后,去指定的目录下着对应的文件
public的文件夹:
//引入核心模块
const http = require('http')
const fs = require('fs')
const path = require('path')
// “策略模式”
// .png --> 'image/png'
// .html --> 'text/html;charset=utf8'
// .js --> 'application/javascript;charset=utf8'
// .css --> 'text/css;charset=utf8'
const obj = {
".png":"image/png",
".jpg":"image/jpg",
".html":"text/html;charset=utf8",
".js":"application/javascript;charset=utf8",
".css":"text/css;charset=utf8"
}
//使用createServer来创建服务
const server = http.createServer((req, res) => {
//获取浏览器请求的url,并且如果只有域名:端口就加载index.html
const url = req.url === '/' ? './index.html' : req.url
//把所有的静态资源全部放在public文件夹下,根据浏览器url获取public下的静态资源
const filepath = path.join(__dirname, 'public', url)
//读取public下的文件
fs.readFile(filepath, (err, data) => {
if (err) {
//如果public下没有此静态资源,会出现以下信息
res.statusCode = 404
res.end('no find')
}
//获取静态资源后缀名
const extname = path.extname(filepath)
//如果obj对象存在这个成员,添加对象的响应头
if (obj[extname]) {
// 设置响应头
res.setHeader('content-type',obj[extname])
}
//返回读出来的信息
res.end(data)
})
})
//使用listener来启动服务
server.listen(8083, () => {
console.log('8083服务器启动啦!!!!')
})