利用nodejs实现简单的静态文件托管

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)

相关推荐

  1. 利用nodejs实现简单静态文件托管

    2024-07-11 18:06:06       20 阅读
  2. Node】使用Node.js构建简单静态页面生成器

    2024-07-11 18:06:06       35 阅读
  3. HuggingFace学习笔记--利用API实现简单NLP任务

    2024-07-11 18:06:06       51 阅读
  4. php简单路由实现静态

    2024-07-11 18:06:06       35 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-11 18:06:06       101 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-11 18:06:06       109 阅读
  3. 在Django里面运行非项目文件

    2024-07-11 18:06:06       87 阅读
  4. Python语言-面向对象

    2024-07-11 18:06:06       96 阅读

热门阅读

  1. 力扣题解( 最长递增子序列)

    2024-07-11 18:06:06       28 阅读
  2. less和sass有啥区别哪个更加好

    2024-07-11 18:06:06       26 阅读
  3. 7.10飞书一面面经

    2024-07-11 18:06:06       27 阅读
  4. mysql bit 对gorm使用何种类型?

    2024-07-11 18:06:06       29 阅读
  5. python爬虫学习(三十三天)---多线程上篇

    2024-07-11 18:06:06       26 阅读