我們來簡單的實(shí)現(xiàn)一下靜態(tài)文件托管
- 先來構(gòu)建一個基礎(chǔ)服務(wù)器
//引入相關(guān)模塊
const http = require('http'),
fs = require('fs');
//創(chuàng)建服務(wù)器
const serv = http.createServer((req, res) => {
//...
});
//監(jiān)聽
serv.listen(3000);
- 對路由進(jìn)行判斷塞琼,如果不存在路徑上則返回404
//是否為GET請求及
if (req.method == "GET") {
//檢查是否為/images路徑下的png文件(此例子只對png文件處理)
if (req.url.substr(0, 7) == "/images" && req.url.substr(-4) == '.png') {
} else if (req.url == '/') {
} else {
res.writeHead(404, { 'Content-Type': 'text/html;charset=utf-8' });
res.end('<h1>當(dāng)前頁面不存在腋寨!</h1>');
}
}
- 對請求文件進(jìn)行判斷梅誓,沒則返回空
fs.stat(__dirname + req.url, (err, stat) => {
if (err || !stat.isFile()) {
res.writeHead(404);
res.end('文件不存在');
return;
}
});
- 對文件進(jìn)行處理,并輸出
// 文件處理
function serve(path, type) {
res.writeHead(200, { 'Content-Type': type });
//文件讀取奶赠,并輸出文件
fs.createReadStream(path).pipe(res);
}
- 組合起來
//引入相關(guān)模塊
const http = require('http'),
fs = require('fs');
//創(chuàng)建服務(wù)器
const serv = http.createServer((req, res) => {
//是否為GET請求及
if (req.method == "GET") {
//檢查是否時(shí)/images路徑下的
if (req.url.substr(0, 7) == "/images" && req.url.substr(-4) == '.png') {
fs.stat(__dirname + req.url, (err, stat) => {
if (err || !stat.isFile()) {
res.writeHead(404, { 'Content-Type': 'text/html;charset=utf-8' });
res.end('<h1>當(dāng)前文件不存在踩娘!</h1>');
return;
}
serve(__dirname + req.url, "image/png");
});
} else if (req.url == '/') {
serve(__dirname + '/index.html', 'text/html');
} else {
res.writeHead(404, { 'Content-Type': 'text/html;charset=utf-8' });
res.end('<h1>當(dāng)前頁面不存在娘荡!</h1>');
}
}
// 文件處理
function serve(path, type) {
res.writeHead(200, { 'Content-Type': type });
//文件讀取搔谴,并輸出文件
fs.createReadStream(path).pipe(res);
}
});
//監(jiān)聽
serv.listen(3000);
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者