每天一个前端小知识03——Node手写服务器

实现思路

  1. 导入http、fs、path模块
  2. 创建web服务器
  3. 监听request,映射本地文件路径,读取文件并返回
  4. 启动服务器

代码

// 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’);
})

效果图

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_33591873/article/details/127975184