const http = require('http')
const url = require('url')
const path = require('path')
const fs = require('fs')
// 判断文件是否存在的辅助函数
async function getState(filePath) {
try {
return await fs.promises.stat(filePath)
} catch (error) {
return null
}
}
const requestListener = async (req, res) => {
// 解析url地址
const urlObj = url.parse(req.url)
// 拼接服务器端的url地址,拼接时文件名不能以'\'开头表示以根路径开始
const fileUrl = path.resolve(
__dirname,
'public',
urlObj.pathname.substring(1)
)
// 判断文件是否存在
const fileState = await getState(fileUrl)
let fileContent = '' // 文件内容
if (fileState) {
// 判断是否是文件夹
if (fileState.isDirectory()) {
// 自动拼接index.html
let newFileUrl = path.resolve(fileUrl, 'index.html')
fileContent = await fs.promises.readFile(newFileUrl)
res.write(fileContent)
} else {
fileContent = await fs.promises.readFile(fileUrl)
res.write(fileContent)
}
} else {
// 文件不存在
let pageNotFound = path.resolve(__dirname, 'public', '404.html')
fileContent = await fs.promises.readFile(pageNotFound)
res.write(fileContent)
}
res.end()
}
const server = http.createServer(requestListener)
server.on('listening', () => {
console.log('server is running on port 9527')
})
server.listen(9587)
配置nginx作为静态文件托管服务器
2024-07-11 18:06:06 57 阅读