標籤:data 路徑 hand ash XML 頁面 function route jpeg
MIME type的縮寫為(Multipurpose Internet Mail Extensions)代表互連網媒體類型(Internet media type),MIME使用一個簡單的字串組成,最初是為了標識郵件Email附件的類型,在html檔案中可以使用content-type屬性工作表示,描述了檔案類型的互連網標準。
自己總結的小demo:貼出server部分的代碼,每一行代碼都有注釋,有不對的地方,希望大家多多指正哈
var http=require("http");var url=require("url");var fs=require("fs");var path=require("path");var MIME_TYPE = { "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"};function start(router,handle){ function onRequest(request,response){ var pathname=url.parse(request.url).pathname; var filePath; request.setEncoding("utf8"); if(typeof handle[pathname] === ‘function‘){//如果有對應的處理方法 router(handle,pathname,response); }else{ //如果請求的是待用資料。如果沒有,判斷是否是待用資料 filePath= "/public" + url.parse(request.url).pathname; fs.exists(__dirname +filePath,function(err){ if(!err){ response.writeHead(404,{‘content-type‘:‘text/plain‘ }); response.write(‘The Resourse ‘+pathname+‘ was Not Found!‘); response.end(); }else{//檔案存在 //擷取檔案的副檔名稱,如果沒有返回" " var ext = path.extname(filePath); //如果副檔名稱為空白,設定副檔名稱為unknown ext = ext?ext.slice(1) : ‘unknown‘; //根據請求檔案的副檔名稱,佈建要求的類型contentType var contentType = MIME_TYPE[ext] || "text/html"; console.log(filePath); //因為有圖片,預設讀取檔案是以utf8讀取的,擷取不到圖片,需要讀檔案是和返迴文件時都用binary編碼,不然圖片不能正常顯示 fs.readFile(__dirname +filePath,"binary",function(err,data){ if(err){ response.end("<h1>500</h1>伺服器內部錯誤!"); }else{//返回不同的頁面 response.writeHead(200,{‘content-type‘:contentType}); response.end(data.toString(),"binary"); } });//fs.readfile } }); } } http.createServer(onRequest).listen(8888); console.log("Server runing at port:8888."); }exports.start=start;
path.exname(filePath),返回filePath路徑檔案的副檔名,如果filePath以.為結尾,將返回.,如果無副檔名,將返回空
HTTP node靜態資源請求載入demo