1. 程式人生 > 其它 >Node建立web伺服器基本指令

Node建立web伺服器基本指令

const http = require('http')
// 1.2 匯入 fs 模組
const fs = require('fs')
// 1.3 匯入 path 模組
const path = require('path')

// 2.1 建立 web 伺服器
const server = http.createServer()
// 2.2 監聽 web 伺服器的 request 事件
server.on('request', (req, res) => {
  // 3.1 獲取到客戶端請求的 URL 地址
  //     /clock/index.html
  //     /clock/index.css
// /clock/index.js const url = req.url // 3.2 把請求的 URL 地址對映為具體檔案的存放路徑 // const fpath = path.join(__dirname, url) // 5.1 預定義一個空白的檔案存放路徑 let fpath = '' if (url === '/') { fpath = path.join(__dirname, './clock/index.html') } else { // /index.html // /index.css // /index.js fpath = path.join(__dirname, '/clock', url) }
// 4.1 根據“對映”過來的檔案路徑讀取檔案的內容 fs.readFile(fpath, 'utf8', (err, dataStr) => { // 4.2 讀取失敗,向客戶端響應固定的“錯誤訊息” if (err) return res.end('404 Not found.') // 4.3 讀取成功,將讀取成功的內容,響應給客戶端 res.end(dataStr) }) }) // 2.3 啟動伺服器 server.listen(80, () => { console.log('server running at http://127.0.0.1') })