这里需要用到3个模块 http(服务器) path(路径) fs(文件)
首先需要导包
// 导入模块 http
const http = require('http')
// 导入模块 fs
const fs = require('fs')
// 导入模块 path
const path = require('path')
然后再用包
// 创建服务器
const server = http.createServer((request, response) => {
// 获取地址
const url = request.url //类似 /index.html的路径
// 获取绝对地址
const fullPath = path.join(__dirname, 'www', url)
// 读取文件
fs.readFile(fullPath, 'utf8', (err, data) => {
if (err == null) {
response.end(data)
}
else {
// 读取失败
response.end(`
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL ${url} was not found on this server.</p>
</body></html>
`)
}
})
})
最后服务器已经有了,里面的回调函数也写好了,现在只需要开启就可以了
// 开启服务器
server.listen(8167, () => {
console.log('success');
})
补充:
这里需要再Node.js里面的后台服务器里面线运行,才能再浏览器里面看到
所以,我们需要安装
cmder 这个软件
安装完成后是这个样子的
然后就需要再里面运行,其中包含几个常用的快捷键
这里列出几个我常用的
cd 文件夹名 这里表示需要到的路径
clear 清除小黑框里面的代码段
ipconfig 查询本机IP地址
node 文件名 需要运行的文件
好了,今天就说到这里,以后慢慢补充