Nodejs实现的一个静态服务器实例(2)

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文件里创建一个assets的文件夹,里面放入你要浏览的静态文件,比如,index.html,demo.js等。

运行方式为:在命令行里切换到上面的JS的文件目录,然后输入 node JS文件名

浏览器内输入:3333/就会看到效果。

--补上上面代码里缺少的两个模块

mime.js

复制代码 代码如下:


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

复制代码 代码如下:


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

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgxpjs.html