路径拼接相关
path模块内置函数path.join()可以实现路径拼接
__dirname是文件当前路径
const path = require('path')
const fullPath = path.join(__dirname, '/files/index.html')
const fullPath = path.join('a', '/b/c', '../', './d', 'e') // ../可以抵消一层路径, 结果为a/b/d/e
中文乱码
res.setHeader('Content-Type', 'text/html; charset=utf-8') // 固定写法, 使用utf-8解析
end()
const content = '404 Not Found!'
res.end(content) // 终止一次请求, 并返回content
访问路径映射本地文件路径
const url = req.url
const fpath = path.join(__dirname, url)
fs.readFile(fpath, 'utf8', (err, dataStr)=>{
if(err){
return res.end('404 Not Found!')
}
res.end(dataStr)
})