node搭建靜態資源服務器

原生node

const http = require('http')
const url = require('url')
const fs = require('fs')
const path = require('path')
const mime = require('mime')
// 創建服務器對象
const server = http.createServer()
server.on('request', (req, res) => {
  // 獲取請求路徑
  let pathname = url.parse(req.url).pathname;
  pathname = pathname == '/' ? '/index.html' : pathname
  // 如果請求的路徑在服務器端是真實存在,就讀取文件內容
  const type = mime.getType(pathname)
  if (pathname && pathname !== '/favicon.ico') {
    fs.readFile(path.join(__dirname, `public${pathname}`), (error, data) => {
      if (error != null) { // 文件讀取出錯
        res.writeHead(404, {
          'content-type': 'text/html;charset=utf8'
        })
        res.end('找不到文件404')
      } else {
        res.writeHead(200, {
          'content-type': type
        })
        res.end(data)
      }
    })
  }
})
server.listen(3000);

express

const express = require('express')

const app = express()

const path = require('path')

app.use(express.static(path.join(__dirname, './public')))

app.listen(3000, () => {
  console.log('running')
})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章