node.js的http模組建立基本Web伺服器
阿新 • • 發佈:2019-01-02
1 首先下載node.js模組.終端執行命令 2 npm i node -g 3 引入http核心模組 4 const http =require('http') 5 引入檔案系統模組 6 const fs =require('fs') 7 引入檔案絕對路徑模組 8 const path =require('path') 9 建立伺服器物件 10 const server =http.createServer() 11 為server伺服器物件繫結處理函式 12 server.on('request',(req,res)=>{ 13 定義請求地址 14 let url =req.url15 判斷請求url地址,返回對應的html內容 16 if(url==='/') url='/views/index.html' 17 fs.readFile(path.join(__dirname,url),(err,buf)=>{ 18 if(err) return res.end('404,Not found') 19 res.end(buf) 20 }) 21 }) 22 監聽啟動伺服器 23 server.listen(3000,()=>{ 24 console.log(http://127.0.0.1:3000) 25 })