实现思路
- 导入http、fs、path模块
- 创建web服务器
- 监听request,映射本地文件路径,读取文件并返回
- 启动服务器
代码
// 1. 导入http、fs、path模块
const http = require(‘http’)
const fs = require(‘fs’)
const path = require(‘path’)
//2. 创建web服务器
const server = http.createServer()
//3. 监听request
server.on(‘request’, (req, res) => {
// 获取url
const url = req.url
// 映射成本地文件路径
let myPath = ‘’
if (url === ‘/’) {
myPath = path.join(__dirname, ‘./test/index.html’)
} else {
myPath = path.join(__dirname, ‘./test’, url)
}
// 读取文件
fs.readFile(myPath, ‘utf-8’, (err, data) => {
if (err) return res.end(‘404’)
res.end(data)
})
})
//4.启动服务器
server.listen(8888, () => {
console.log(‘8888端口服务器启动了!!!请求路径:localhost:8888’);
})