切换主题
五、实现clock时钟的web服务器案例
js
// 引入fs模块
const fs = require('fs');
// 引入path模块
const path = require('path')
// 引入http模块
const http = require('http');
// 创建http服务器
const server = http.createServer()
// request事件
server.on('request', (req, res) => {
// 用户请求路径
const url = req.url
let fpath = ''
if (url === "/") {
fpath = path.join(__dirname, './clock/index.html');
} else {
fpath = path.join(__dirname, './clock', url)
}
fs.readFile(fpath, 'utf8', (err, data) => {
if (err) return res.end('404 Not Found')
console.log('请求成功!');
// 响应给客户端
res.end(data)
})
})
// 在8080端口运行
server.listen(8080, () => {
console.log('服务器运行了');
})