Node搭建一個簡單的靜態服務器,具有一些基本功能.javascript
功能:css
Node重定向寫法能夠參考stackoverflow.com/questions/4…html
我在文件裏面設置了/static爲靜態資源的文件目錄,所以http://localhost:8080/其實就是默認打開的就是D:\xxx\staticjava
// server.js 這裏其實應該對代碼進行拆分下,稍微整潔點
const http = require('http');
const fs = require('fs');
const path = require('path');
const url = require('url');
var mime = require('./mime'); // 加載咱們的mime.js
var config = require('./config');
const port = 8080;
const server = http.createServer(function(req,res){
var pathName = url.parse(req.url).pathname; // 獲取文件名"/xxx"
// 對中文進行解碼,防止亂碼
pathName = decodeURI(pathName);
// 重定向: 考慮定義標準的url,以'/'結尾.
if(path.extname(pathName) === ''){ // 沒有擴展名
if(pathName.charAt(pathName.length-1) !== '/'){
pathName += '/';
var redirect = encodeURI('http://' + req.headers.host + pathName); // 記得encodeURI,否則中文目錄報錯
console.log(redirect);
res.writeHead(301,{
location: redirect
});
}
}
// 獲取資源的絕對路徑
var realFilePath = path.resolve(__dirname+'/static'+ pathName);
console.log(realFilePath);
// 獲取對應文件的文檔類型
var ext = path.extname(pathName); // 獲取後綴名,如'.html'
ext = ext?ext.slice(1): 'notKnow'; // 取掉.符號
if (ext.match(config.Expires.fileMatch)) {
var expires = new Date();
expires.setTime(expires.getTime() + config.Expires.maxAge * 1000);
// 設置響應頭
res.setHeader("Expires", expires.toUTCString());
res.setHeader("Cache-Control", "max-age=" + config.Expires.maxAge);
}
// 定義未知文檔的類型MIME
var contentType = mime[ext] || "text/plain"; // 後綴名存在就進行映射,不存在就是'text/plain'
// 判斷文件是否存在
fs.stat(realFilePath,function(err,stats){
// err
if(err){
// 也能夠定製本身的404頁面
res.writeHead(404,{'content-type': 'text/html'});
res.end('<h3>404 Not Found</h3>');
}
// 存在
if(stats.isFile()){
console.log('is file');
res.writeHead(200,{'content-type': contentType});
// 開始讀取文件
var stream = fs.createReadStream(realFilePath);
// 讀取時候錯誤處理
stream.on('error',function(){
res.writeHead(500,{'content-type': contentType});
});
// 返回文件內容
stream.pipe(res);
}
// 路徑是目錄的狀況,列出當前目錄下文件
if(stats.isDirectory() ){
var html = '<head><meta charset="utf-8"></head>';
// 讀寫該目錄下的內容 files是文件數組
fs.readdir(realFilePath,function(err,files){
if(err){
console.log('目錄文件讀取失敗');
}else{
console.log('is directory' + files); // test
for(var i = 0;i < files.length;i++){
//測當前目錄下是否有index.html文件
// if (files[i] === "index.html") {
// res.writeHead(200, { "content-type": "text/html" });
// res.end();
// break;
// }
html += "<div><a href='"+files[i]+"'>"+files[i]+"</a></div>";
}
}
res.writeHead(200,{'content-type': 'text/html'});
res.end(html);
});
}
});
}).listen(port,function(){
console.log('Server running at port:' + port)
});複製代碼
// config.js
exports.Expires = {
fileMatch: /^(gif|png|jpg|js|css)$/ig, // 這只是個demo
maxAge: 60 * 60 * 24 * 365
};複製代碼
//mime.js 其實早就有這種模塊的.
module.exports = {
"css": "text/css",
"gif": "image/gif",
"html": "text/html",
"ico": "image/x-icon",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"js": "text/javascript",
"json": "application/json",
"pdf": "application/pdf",
"png": "image/png",
"svg": "image/svg+xml",
"swf": "application/x-shockwave-flash",
"tiff": "image/tiff",
"txt": "text/plain",
"wav": "audio/x-wav",
"wma": "audio/x-ms-wma",
"wmv": "video/x-ms-wmv",
"xml": "text/xml"
};複製代碼
參考資料:www.infoq.com/cn/news/201…json
if(stats.isFile()){
^
TypeError: Cannot read property 'isFile' of undefined複製代碼