Node.js 原生 API 搭建 Web 服务器

IT科技类资讯2025-11-05 04:20:2517
Node.js 原生 API 搭建 Web 服务器
复制use strict const http = require(http)  const url = require(url)  const fs = require(fs)  const path = require(path)  const cp = require(child_process)  const port = 8080  const hostname = localhost // 创建 http 服务  let httpServer = http.createServer(processStatic)  // 设置监听端口  httpServer.listen(port,原生 hostname, () => {      console.log(`app is running at port:${port}`)      console.log(`url: http://${hostname}:${port}`)    cp.exec(`explorer http://${hostname}:${port}`, () => {}) })  // 处理静态资源  function processStatic(req, res) {      const mime = {      css: text/css,      gif: image/gif,      html: text/html,      ico: image/x-icon,      jpeg: image/jpeg,      jpg: image/jpeg,      js: text/javascript,      json: application/json,      pdf: application/pdf,      png: image/png,      svg: image/svg+xml,      woff: application/x-font-woff,      woff2: application/x-font-woff,      swf: application/x-shockwave-flash,      tiff: image/tiff,      txt: text/plain,      wav: audio/x-wav,      wma: audio/x-ms-wma,      wmv: video/x-ms-wmv,      xml: text/xml   }      const requestUrl = req.url      let pathName = url.parse(requestUrl).pathname      // 中文乱码处理    pathName = decodeURI(pathName)      let ext = path.extname(pathName)      // 特殊 url 处理    if (!pathName.endsWith(/) && ext ===  && !requestUrl.includes(?)) {      pathName += /     const redirect = `http://${req.headers.host}${pathName}`      redirectUrl(redirect, res)    }      // 解释 url 对应的资源文件路径    let filePath = path.resolve(__dirname + pathName)      // 设置 mime     ext = ext ? ext.slice(1) : unknown   const contentType = mime[ext] || text/plain   // 处理资源文件    fs.stat(filePath, (err, stats) => {          if (err) {        res.writeHead(404, { content-type: text/html;charset=utf-8 })        res.end(<h1>404 Not Found</h1>)              return     }          // 处理文件      if (stats.isFile()) {        readFile(filePath, contentType, res)      }          // 处理目录      if (stats.isDirectory()) {              let html = "<head><meta charset = utf-8/></head><body><ul>"       // 遍历文件目录,IT技术网以超链接返回,网站模板服务方便用户选择        fs.readdir(filePath,原生 (err, files) => {                  if (err) {            res.writeHead(500, { content-type: contentType })            res.end(<h1>500 Server Error</h1>)            return         } else {                      for (let file of files) {                          if (file === index.html) {                              const redirect = `http://${req.headers.host}${pathName}index.html`                redirectUrl(redirect, res)              }              html += `<li><a href=${file}>${file}</a></li>`            }            html += </ul></body>           res.writeHead(200, { content-type: text/html })            res.end(html)          }        })      }    })  }  // 重定向处理  function redirectUrl(url, res) {    url = encodeURI(url)    res.writeHead(302, {      location: url    })    res.end()  }  // 文件读取  function readFile(filePath, contentType, res) {    res.writeHead(200, { content-type: contentType })    const stream = fs.createReadStream(filePath)    stream.on(error, function() {      res.writeHead(500, { content-type: contentType })      res.end(<h1>500 Server Error</h1>)    })    stream.pipe(res)  }  1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.39.40.41.42.43.44.45.46.47.48.49.50.51.52.53.54.55.56.57.58.59.60.61.62.63.64.65.66.67.68.69.70.71.72.73.74.75.76.77.78.79.80.81.82.83.84.85.86.87.88.89.90.91.92.93.94.95.96.97.98.99.100.101.102.103.104.105.106.107.108.109.110.111.112.113.114.高防服务器
本文地址:http://www.bzuk.cn/html/245b6699688.html
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

全站热门

oppo手机边充电边玩的危害与防范(揭秘oppo手机边充电边玩的危害以及如何正确使用)

揭秘钻石音箱的无与伦比音质与奢华外观(全面解析钻石音箱的顶级音质及其独特设计)

探索Alza的产品特点和用户体验(解密Alza的创新技术与用户评价)

以胜算充电宝(胜算充电宝-为你的移动设备提供安全可靠的能量支持)

手工制作电脑支架蛋糕教程(用简单材料打造独特创意,将甜点与科技相结合)

雷瓦洁面仪的使用体验及效果分析(雷瓦洁面仪的关键特点、使用方法和真实用户评价)

揭秘松下洁面仪(松下洁面仪究竟如何实现洁净无比的肌肤?)

小米SIM卡欠费后果及处理方法(了解小米SIM卡欠费会导致的后果以及如何处理)

友情链接

滇ICP备2023006006号-33