Node.js模塊封裝

靜態服務功能(將對應路徑的文件內容返回到瀏覽器)

環境:node12.10.0、引入文件:mime.json

//staticServer模塊
const fs = require('fs');
const path = require('path');
const mime = require('./lib/mime.json');  //用於通過文件後綴設置響應頭
exports.staticServer = (req, res, rootpath) => {
  fs.readFile(path.join(rootpath, req.url), (err, fileContent) => {
    if (err) {
      //第一個參數爲響應狀態碼
      res.writeHead(404, {
        'Content-Type': 'text/plain;charset=utf8'//設置響應類型和編碼,解決亂碼
      })
      res.end("404頁面找不到了");//終止響應,不可以多次寫入
    } else {
      let dtype = "text/html";  //設置默認類型
      let ext = path.extname(req.url);
      if (mime[ext]) {
        dtype = mime[ext];  //通過文件後綴獲取對應類型
      }

      if (dtype.startsWith('text')) {
        dtype += ';charset=utf8';  //響應內容爲文本的時候設置編碼
      }
      res.writeHead(200, {
        'Content-Type': dtype
      })
      res.end(fileContent);
    }
  })
}
  • 測試代碼(啓動服務,通過127.0.0.1:3000/index.html訪問到項目目錄下www目錄中的文件內容)
//server.js
const http = require('http');
const ss = require('./staticServer.js');
const path = require('path');

http.createServer((req, res) => {
  ss.staticServer(req, res, path.join(__dirname, 'www'));
}).listen(3000, () => {
  console.log("服務running");
})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章