由于我们无法事先得知一个.html文件中会引用多少个静态资源(.png, .css, .js....),所以,我们不能像处理某个页面一样去处理它们。
我们的解决办法是:
-
把所有的静态资源(.html,.png,.css,.js)全放在一个指定的目录里;
-
收到用户的请求之后,去指定的目录下去找对应的文件
-
找到,把内容读出来返回给用户。
-
找不到,报404。
-
目录如下:
|-public
|-public/index.html
|-public/stye.css
|-public/1.png
|-server.js
把所有的静态资源全放在public下面,使用server.js来启动web服务器
代码
//加载模块
const http = require('http')
const fs = require('fs')
const path = require('path')
// "策略模式"
const obj = {
".png": "image/png",
".jpg": "image/jpg",
".html": "text/html;charset=utf8",
".js": "application/javascript;charset=utf8",
".css": "text/css;charset=utf8"
}
// req请求过程 //res响应结果
let server = http.createServer((req, res) => {
//当地址栏地址为/时 默认地址是index.html
const url = req.url === '/' ? 'index.html' : req.url
//用内置模块将地址拼接成绝对地址 并且是动态的
const filePath = path.join(__dirname, 'publie', url)
// 读入文件
fs.readFile(filePath, (err, data) => {
if (err) {
req.statusCode = 404
res.end('not found')
} else {
//将地址的后缀文件名截取
const extName = path.extname(filePath)
//当 obj的值存在 给响应头设置一个该后缀名所需要的请求体
if (obj[extName]) {
//设置响应头为 obj中对应类型
res.setHeader('content-type', obj[extName])
}
res.end(data)
}
})
})
server.listen(5613)