国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 語(yǔ)言 > JavaScript > 正文

Node.js原生api搭建web服務(wù)器的方法步驟

2024-05-06 15:42:23
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

node.js 實(shí)現(xiàn)一個(gè)簡(jiǎn)單的 web 服務(wù)器還是比較簡(jiǎn)單的,以前利用 express 框架實(shí)現(xiàn)過(guò)『nodeJS搭一個(gè)簡(jiǎn)單的(代理)web服務(wù)器』。代碼量很少,可是使用時(shí)需要安裝依賴,多處使用難免有點(diǎn)不方便。于是便有了完全使用原生 api 來(lái)重寫(xiě)的想法,也當(dāng)作一次 node.js 復(fù)習(xí)。

1、靜態(tài) web 服務(wù)器

'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'  // 創(chuàng)建 http 服務(wù) let httpServer = http.createServer(processStatic) // 設(shè)置監(jiān)聽(tīng)端口 httpServer.listen(port, hostname, () => {   console.log(`app is running at port:${port}`)   console.log(`url: http://${hostname}:${port}`)  cp.exec(`explorer http://${hostname}:${port}`, () => {}) }) // 處理靜態(tài)資源 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 對(duì)應(yīng)的資源文件路徑  let filePath = path.resolve(__dirname + pathName)   // 設(shè)置 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>"    // 遍歷文件目錄,以超鏈接返回,方便用戶選擇    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) }             
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 平舆县| 尚志市| 蚌埠市| 耒阳市| 三都| 历史| 凤翔县| 格尔木市| 洛扎县| 奇台县| 徐汇区| 南宁市| 肥乡县| 南皮县| 泰顺县| 临武县| 睢宁县| 荔波县| 贵南县| 涞源县| 会理县| 尤溪县| 乐亭县| 平和县| 松溪县| 赤水市| 靖西县| 翁牛特旗| 独山县| 神农架林区| 宜宾县| 图木舒克市| 浮山县| 苏州市| 长子县| 西林县| 白山市| 庆云县| 乌兰浩特市| 安阳县| 凭祥市|