網(wǎng)站項目是在網(wǎng)上隨便找的,文件夾名稱為static
導(dǎo)入模塊
const http = require('http');
const fs = require('fs');
const url = require('url');
const path = require('path');
創(chuàng)建服務(wù)器,并在其中加載網(wǎng)站
- 通過http.createServer()創(chuàng)建一個服務(wù)器
const server = http.createServer(function (req, res) {}
- 聲明變量pathname , 格式化URL
let pathname = url.parse(req.url).pathname;
- 判斷請求地址
- 當(dāng)pathname=='/' 時,通過fs.readFile()讀取首頁index.html
if (pathname == '/' || pathname == '/index') {
fs.readFile('./static/index.html', function (err, data) {
if (err) {
fs.readFile('./static/404.html', function (err) {
if (err) throw err;
res.end(data);
})
}
res.setHeader('Content-Type', 'text/html;charset=utf8');
res.end(data);
})
}
- else
//獲取后綴名
let suffix = path.extname(pathname);
// 聲明mime變量,等于mime值 例:text/html
let mime = getExtName(suffix);
- 加載請求到的文件
fs.readFile('./static/' + pathname, function (err, data) {
//響應(yīng)頭
res.setHeader('Content-Type', mime + ';charset=utf8');
res.end(data)
})
完整服務(wù)器代碼
const server = http.createServer(function (req, res) {
let pathname = url.parse(req.url).pathname;
// console.log(pathname)
if (pathname == '/' || pathname == '/index') {
fs.readFile('./static/index.html', function (err, data) {
if (err) {
fs.readFile('./static/404.html', function (err) {
if (err) throw err;
res.end(data);
})
}
// res.setHeader('Content-Type', 'text/html;charset=utf8');
res.end(data);
// console.log(data.toString())
})
} else {
//獲取后綴名
let suffix = path.extname(pathname);
let mime = getExtName(suffix);
fs.readFile('./static/' + pathname, function (err, data) {
res.setHeader('Content-Type', mime + ';charset=utf8');
res.end(data)
})
}
})
server.listen('3000', '127.0.0.1')
判斷文件類型,返回對應(yīng)的響應(yīng)頭(在服務(wù)器外部判斷)
// 上圖代碼
res.setHeader('Content-Type', mime + ';charset=utf8');
function getExtName(suffix) {
// console.log(suffix)
switch (suffix) {
case '.html':
return 'text/html';
case '.css':
return 'text/css';
case '.js':
return 'text/javascript';
case '.jpg':
return 'images/jpg';
case '.png':
return 'images/png';
default:
return 'text/plain';
}
}