1. response.statusCode = 200
    2. const filePath = path === '/' ? '/index.html' : path // 默认index.html
    3. // 识别后缀
    4. const index = filePath.lastIndexOf('.')
    5. const suffix = filePath.substring(index)
    6. const fileType = {
    7. ".html": "text/html",
    8. ".js": "text/javascript",
    9. ".css": "text/css",
    10. ".json": "text/json",
    11. ".png": "image/png",
    12. ".jpg": "image/jpeg"
    13. }
    14. response.setHeader('Content-Type',
    15. `${fileType[suffix] || 'text/html'};charset=utf-8`)
    16. // 处理错误
    17. let content
    18. try{
    19. content = fs.readFileSync(`./public${filePath}`)
    20. }catch(error){
    21. content = "文件不存在"
    22. response.statusCode = 404
    23. }
    24. response.write(content)
    25. response.end()