学习笔记 内容待商榷 欢迎评论区指出错误
1.导入模块
const http = require('http')
const url = require('url')
const path = require('path')
const fs = require('fs')
const mime = require('mime')
mime模块获取文档type类型
app.on('request', (req, res) => {
// let pathname = url.parse(req.url).pathname
let pathname = req.url //获取路径 默认是'/'
//console.log(req.url);
pathname = pathname == '/' ? '/default.html' : pathname
let realpath = path.join(__dirname, 'public' + pathname)//__dirname 指向绝对路径 path.join会把字符串拼接起来 攒成路径
let type = mime.getType(realpath);
fs.readFile(realpath, (error, result) => {
if (error != null) {
res.writeHead(404, {
'content-type': 'text/html;charset=utf8'
})
res.end('文件读取失败')
return
}
res.writeHead(200, {
'content-type': type //向客户端发送响应头 指定里面响应的个文件的类型
})
res.end(result)
})
})