国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

Node.js靜態(tài)文件服務(wù)器改進(jìn)版

2019-11-20 10:49:40
字體:
供稿:網(wǎng)友

首先還是先感謝github,感謝github上提供此段源碼的作者。跟昨晚的來比今天的靜態(tài)文件服務(wù)器有點(diǎn)點(diǎn)復(fù)雜些,可以學(xué)到很多新的東西。

仔細(xì)會發(fā)現(xiàn)這次的代碼多了一個fs.stat函數(shù)和ReadStream對象的pipe函數(shù),stat這個函數(shù)是用來獲取文件信息。第一個參數(shù)是傳入文件路徑,第二個則是回調(diào)函數(shù),回調(diào)函數(shù)的第二個參數(shù)stats的屬性為文件的基本信息。pipe函數(shù)用于將這個可讀流和destination目標(biāo)可寫流連接起來,傳入這個流中的數(shù)據(jù)將會寫入到destination流中。通過在必要時暫停和恢復(fù)流,來源流和目的流得以保持同步。

該靜態(tài)文件服務(wù)器的改進(jìn)點(diǎn)在于使用了Last-Modified和If-Modified-Since報文頭,可以不必要給瀏覽器返回它已經(jīng)存在的文件。順便可以根據(jù)瀏覽器請求資源的壓縮方式返回給資源進(jìn)行g(shù)zip或者deflate壓縮。

var PORT = 8000;var http = require("http");var url = require("url");var fs = require("fs");var path = require("path");var mime = require("./mime").types;var config = require("./config");var zlib = require("zlib");var server = http.createServer(function(request, response) { response.setHeader("Server", "Node/V5"); var pathname = url.parse(request.url).pathname; console.log("url = " + pathname); if (pathname.slice(-1) === "/") {  pathname = pathname + config.Welcome.file; } var realPath = __dirname + "/" + path.join("assets", path.normalize(pathname.replace(//././g, ""))); console.log("realPath = " + realPath); var pathHandle = function (realPath) {  fs.stat(realPath, function (err, stats) {   if (err) {    response.writeHead(404, "Not Found", {'Content-Type': 'text/plain'});    response.write("stats = " + stats);    response.write("This request URL " + pathname + " was not found on this server.");    response.end();   } else {    if (stats.isDirectory()) {     realPath = path.join(realPath, "/", config.Welcome.file);     pathHandle(realPath);    } else {     var ext = path.extname(realPath);     ext = ext ? ext.slice(1) : 'unknown';     var contentType = mime[ext] || "text/plain";     response.setHeader("Content-Type", contentType);     //獲得文件的修改時間      var lastModified = stats.mtime.toUTCString();     var ifModifiedSince = "If-Modified-Since".toLowerCase();     //設(shè)置Last-Modified     //服務(wù)器給瀏覽器返回文件最后一次修改時間Last-Modified     response.setHeader("Last-Modified", lastModified);     if (ext.match(config.Expires.fileMatch)) {      var expires = new Date();      expires.setTime(expires.getTime() + config.Expires.maxAge * 1000);      response.setHeader("Expires", expires.toUTCString());      response.setHeader("Cache-Control", "max-age=" + config.Expires.maxAge);     }     //服務(wù)器接收瀏覽器發(fā)送過來的If-Modified-Since報文頭     //日期相同表示該資源沒有變化則返回304     //告訴瀏覽器該資源你已經(jīng)有了,不需要再請求了     if (request.headers[ifModifiedSince] && lastModified == request.headers[ifModifiedSince]) {      response.writeHead(304, "Not Modified");      response.end();     } else {      var raw = fs.createReadStream(realPath);      var acceptEncoding = request.headers['accept-encoding'] || "";      var matched = ext.match(config.Compress.match);       if (matched && acceptEncoding.match(//bgzip/b/)) {       response.writeHead(200, "Ok", {'Content-Encoding': 'gzip'});       raw.pipe(zlib.createGzip()).pipe(response);      } else if (matched && acceptEncoding.match(//bdeflate/b/)) {       response.writeHead(200, "Ok", {'Content-Encoding': 'deflate'});       raw.pipe(zlib.createDeflate()).pipe(response);      } else {       response.writeHead(200, "Ok");       raw.pipe(response);      }     }    }   }  }); }; pathHandle(realPath);});server.listen(PORT);console.log("Server runing at port: " + PORT + ".");

Expires字段聲明了一個網(wǎng)頁或URL地址不再被瀏覽器緩存的時間,一旦超過了這個時間,瀏覽器都應(yīng)該聯(lián)系原始服務(wù)器。這里設(shè)置失效時間為1年。

exports.Expires = { fileMatch: /^(gif|png|jpg|js|css)$/ig, maxAge: 60*60*24*365};exports.Compress = { match: /css|js|html/ig};exports.Welcome = { file: "index.html"};

枚舉各種資源的類型,可根據(jù)擴(kuò)展名設(shè)置Content-Type。

exports.types = { "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"};

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 德州市| 秭归县| 南宁市| 济阳县| 石楼县| 得荣县| 桑日县| 阿坝县| 廊坊市| 黄冈市| 永胜县| 建平县| 新郑市| 东莞市| 鹤峰县| 常山县| 金溪县| 井冈山市| 怀宁县| 长岭县| 蒲江县| 建宁县| 年辖:市辖区| 通化市| 遵义市| 库尔勒市| 黔西| 湖北省| 青川县| 吴忠市| 凌源市| 荥阳市| 舒城县| 莲花县| 湖南省| 鹤山市| 柳河县| 旬邑县| 永福县| 新兴县| 淳化县|