node筆記 --祈粼
const http = require('http') // 獲取http模塊
const url = require('url') // 獲取url模塊
const fs = require('fs') // 獲取fs模塊 fileSystem
const path = require('path') // path模塊提供了一些用戶處理文件路徑的小工具
// 創(chuàng)建服務(wù)
const server = http.createServer((req, res) => {
if (req.url == 'favicon') return;
// 獲取端口號(hào)以后的URL
let pathname = url.parse(req.url).pathname
// 判斷是文件還是文件夾
if (pathname.indexOf('.') < 0) {
pathname += '/index.html'
}
// 獲取文件名
let fileUrl = './' + path.normalize(pathname)
// 獲取后綴名
let extname = path.extname(fileUrl)
// 讀取需要加載的文件
fs.readFile(fileUrl, (err, data) => {
// 錯(cuò)誤返回404
if (err) { //一般情況下都是路徑引起的錯(cuò)誤
res.writeHead(404, { "Content-type": "text/html;charset=UTF-8" });
res.end("404衩椒,頁(yè)面未找到,page not found");
}
// 獲取content-type并返回
getMime(extname, (mime) => {
res.writeHead(200, { 'Content-type': mime })
res.end(data)
})
})
})
const getMime = (mime, callback) => {
// 讀取文件類型的JSON 根據(jù)后綴來(lái)判斷文件的類型
fs.readFile('./mime.json', (err, data) => {
if (err) throw err;
let datas = JSON.parse(data)
callback(datas[mime])
})
}
// 監(jiān)聽端口號(hào)和訪問(wèn)地址
server.listen(3000, '127.0.0.1')