整体架构目录
    image.png
    创建index.html 和引入相关资源

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8" />
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    7. <title>public</title>
    8. <link rel="icon" href="data:image/ico;base64,aWNv" />
    9. <link rel="stylesheet" href="./styles/reset.css" />
    10. </head>
    11. <body>
    12. public
    13. <script src="./scripts/common.js"></script>
    14. <img src="./images/test.png" alt="" />
    15. </body>
    16. </html>

    创建服务server.js

    1. const http = require('http')
    2. const path = require('path')
    3. const readStaticFile = require('./readStaticFile')
    4. http.createServer(async (req, res) => {
    5. // 获取url
    6. let urlString = req.url
    7. let filePathName = path.join(__dirname, './public', urlString)
    8. // 根据url, 去public目录下读取数据
    9. // 如果你调用的方法是一个异步函数,在获取结果的时候,一定要await
    10. let result
    11. try {
    12. result = await readStaticFile(filePathName, res)
    13. var { data, mimeType } = result
    14. } catch {
    15. console.log(result)
    16. }
    17. // 把获取的结果, 返回给前端
    18. res.writeHead(200, {
    19. 'content-type': `${mimeType}; charset=utf-8`
    20. })
    21. res.write(data)
    22. res.end()
    23. }).listen(2139, () => console.log('localhost:2139'))

    创建自定义fs工具

    1. const path = require('path')
    2. const mime = require('mime')
    3. const fs = require('fs')
    4. // 读取文件内容,因为readFile是异步函数,为了调用者不立刻返回值,
    5. // 需要封装一个promise, 让调用者有机会等待结果
    6. function myReadFile(file) {
    7. return new Promise((resolve, reject) => {
    8. fs.readFile(file, (err, data) => {
    9. if (err) {
    10. reject('你访问的是一个文件夹,且文件夹里没有index.html')
    11. // resolve('你访问的是一个文件夹,且文件夹里没有index.html')
    12. } else {
    13. resolve(data)
    14. }
    15. })
    16. })
    17. }
    18. async function readStaticFile(filePathName) {
    19. let ext = path.parse(filePathName).ext
    20. let mimeType = mime.getType(ext) || 'text/html'
    21. let data
    22. // 判断文件是否存在
    23. if (fs.existsSync(filePathName)) {
    24. if (ext) {
    25. // myReadFile(filePathName)
    26. // .then(result => data = result)
    27. // .catch((err) => data = err)
    28. data = await myReadFile(filePathName)
    29. } else {
    30. // myReadFile(path.join(filePathName, '/index.html'))
    31. // .then(result => data = result)
    32. // .catch((err) => data = err)
    33. data = await myReadFile(path.join(filePathName, '/index.html'))
    34. }
    35. } else {
    36. data = 'file or folder not found.'
    37. }
    38. return {
    39. data,
    40. mimeType
    41. }
    42. }
    43. module.exports = readStaticFile