【nodejs】nodejs創建服務器並且返回靜態資源(7)

//創建網站服務器的模塊
const http = require('http')
const path = require('path')
const fs = require('fs')
const url= require('url')
//mime模塊可以根據當前的請求路徑,分析出資源類型來,設計出類型
const mime = require('mime')
//處理請求參數模塊
const querystring = require('querystring')

//app是網站服務器對象
const app = http.createServer()

app.on('request',(req,res)=>{

    const method = req.method.toLowerCase();
    let {pathname} = url.parse(req.url,true)

    pathname = pathname == '/'?'/index.html':pathname


    let realPath = path.join(__dirname,'public'+pathname)
    let type = mime.getType(realPath);  //根據路徑獲取文件類型;高級瀏覽器中不用

    fs.readFile(realPath,(error,result)=>{
        if(error != null){
            res.writeHead(404,{
                'content-type':'text/html;charset=utf-8'
            })
            res.end('文件讀取失敗')
            return;
        }
        res.writeHead(200,{
            'content-type':type
        })
        res.end(result)

    })
});


app.listen(3000)
console.log('網站服務器啓動成功')

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章