整体架构目录
创建index.html 和引入相关资源
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>public</title>
<link rel="icon" href="data:image/ico;base64,aWNv" />
<link rel="stylesheet" href="./styles/reset.css" />
</head>
<body>
public
<script src="./scripts/common.js"></script>
<img src="./images/test.png" alt="" />
</body>
</html>
创建服务server.js
const http = require('http')
const path = require('path')
const readStaticFile = require('./readStaticFile')
http.createServer(async (req, res) => {
// 获取url
let urlString = req.url
let filePathName = path.join(__dirname, './public', urlString)
// 根据url, 去public目录下读取数据
// 如果你调用的方法是一个异步函数,在获取结果的时候,一定要await
let result
try {
result = await readStaticFile(filePathName, res)
var { data, mimeType } = result
} catch {
console.log(result)
}
// 把获取的结果, 返回给前端
res.writeHead(200, {
'content-type': `${mimeType}; charset=utf-8`
})
res.write(data)
res.end()
}).listen(2139, () => console.log('localhost:2139'))
创建自定义fs工具
const path = require('path')
const mime = require('mime')
const fs = require('fs')
// 读取文件内容,因为readFile是异步函数,为了调用者不立刻返回值,
// 需要封装一个promise, 让调用者有机会等待结果
function myReadFile(file) {
return new Promise((resolve, reject) => {
fs.readFile(file, (err, data) => {
if (err) {
reject('你访问的是一个文件夹,且文件夹里没有index.html')
// resolve('你访问的是一个文件夹,且文件夹里没有index.html')
} else {
resolve(data)
}
})
})
}
async function readStaticFile(filePathName) {
let ext = path.parse(filePathName).ext
let mimeType = mime.getType(ext) || 'text/html'
let data
// 判断文件是否存在
if (fs.existsSync(filePathName)) {
if (ext) {
// myReadFile(filePathName)
// .then(result => data = result)
// .catch((err) => data = err)
data = await myReadFile(filePathName)
} else {
// myReadFile(path.join(filePathName, '/index.html'))
// .then(result => data = result)
// .catch((err) => data = err)
data = await myReadFile(path.join(filePathName, '/index.html'))
}
} else {
data = 'file or folder not found.'
}
return {
data,
mimeType
}
}
module.exports = readStaticFile