最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Nodejs實現(xiàn)的一個靜態(tài)服務(wù)器實例

 更新時間:2014年12月06日 14:09:45   投稿:junjie  
這篇文章主要介紹了Nodejs實現(xiàn)的一個靜態(tài)服務(wù)器實例,本文實現(xiàn)的靜態(tài)服務(wù)器實例包含cache功能、壓縮功能等,需要的朋友可以參考下

參考cnodejs.org上面的靜態(tài)服務(wù)器例子,寫了下面的一個nodejs靜態(tài)服務(wù)器例子,里面包含cache,壓縮,貼代碼如下:

復(fù)制代碼 代碼如下:

/**
 * 靜態(tài)文件服務(wù)器測試?yán)?br />  * User: xuwm
 * Date: 13-5-17
 * Time: 上午8:38
 * To change this template use File | Settings | File Templates.
 */
var port=3333;
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");
//創(chuàng)建http服務(wù)端
var server=http.createServer(function(request,response){
    var obj= url.parse(request.url);
    response.setHeader("Server","Node/V8");
    console.log(obj);
    var pathname=obj.pathname;
    if(pathname.slice(-1)==="/"){
        pathname=pathname+config.Welcome.file;   //默認(rèn)取當(dāng)前默認(rèn)下的index.html
    }
    var realPath = path.join("assets", path.normalize(pathname.replace(/\.\./g, "")));
    console.log(realPath) ;
    var pathHandle=function(realPath){
    //用fs.stat方法獲取文件
        fs.stat(realPath,function(err,stats){
            if(err){
                response.writeHead(404,"not found",{'Content-Type':'text/plain'});
                response.write("the request "+realPath+" is not found");
                response.end();
            }else{
                if(stats.isDirectory()){
                }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();
                    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);
                    }

                    if (request.headers[ifModifiedSince] && lastModified == request.headers[ifModifiedSince]) {
                        console.log("從瀏覽器cache里取")
                        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("http server run in port:"+port);

首先需要在JS文件里創(chuàng)建一個assets的文件夾,里面放入你要瀏覽的靜態(tài)文件,比如,index.html,demo.js等。

運行方式為:在命令行里切換到上面的JS的文件目錄,然后輸入 node JS文件名

瀏覽器內(nèi)輸入http://localhost:3333/就會看到效果。

--補上上面代碼里缺少的兩個模塊

mime.js

復(fù)制代碼 代碼如下:

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"
};

config.js

復(fù)制代碼 代碼如下:

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"
};

相關(guān)文章

最新評論

长武县| 冕宁县| 大冶市| 朔州市| 上高县| 南岸区| 昌吉市| 合水县| 江城| 成安县| 喀喇沁旗| 宜宾市| 崇阳县| 临泉县| 科技| 聂荣县| 廊坊市| 前郭尔| 日喀则市| 武功县| 商河县| 沂源县| 遂平县| 时尚| 子长县| 宣威市| 德清县| 休宁县| 扎鲁特旗| 佛坪县| 杭州市| 交口县| 咸丰县| 盐山县| 平顶山市| 丰台区| 石狮市| 惠来县| 玉屏| 枞阳县| 宁乡县|