Nodejs實(shí)現(xiàn)的一個(gè)靜態(tài)服務(wù)器實(shí)例
參考cnodejs.org上面的靜態(tài)服務(wù)器例子,寫(xiě)了下面的一個(gè)nodejs靜態(tài)服務(wù)器例子,里面包含cache,壓縮,貼代碼如下:
/**
* 靜態(tài)文件服務(wù)器測(cè)試?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)建一個(gè)assets的文件夾,里面放入你要瀏覽的靜態(tài)文件,比如,index.html,demo.js等。
運(yùn)行方式為:在命令行里切換到上面的JS的文件目錄,然后輸入 node JS文件名
瀏覽器內(nèi)輸入http://localhost:3333/就會(huì)看到效果。
--補(bǔ)上上面代碼里缺少的兩個(gè)模塊
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"
};
- nodejs express配置自簽名https服務(wù)器的方法
- 深入理解nodejs搭建靜態(tài)服務(wù)器(實(shí)現(xiàn)命令行)
- nodejs構(gòu)建本地web測(cè)試服務(wù)器 如何解決訪問(wèn)靜態(tài)資源問(wèn)題
- 用Nodejs搭建服務(wù)器訪問(wèn)html、css、JS等靜態(tài)資源文件
- 在windows上用nodejs搭建靜態(tài)文件服務(wù)器的簡(jiǎn)單方法
- 使用nodejs、Python寫(xiě)的一個(gè)簡(jiǎn)易HTTP靜態(tài)文件服務(wù)器
- nodejs發(fā)布靜態(tài)https服務(wù)器的方法
相關(guān)文章
基于nodejs+express4.X實(shí)現(xiàn)文件下載的實(shí)例代碼
本篇文章主要介紹了詳解nodejs+express4.X的文件下載的實(shí)例代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-07-07在node.js中怎么屏蔽掉favicon.ico的請(qǐng)求
這篇文章主要介紹了在node.js中怎么屏蔽掉favicon.ico的請(qǐng)求,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2017-03-03Node.js文件系統(tǒng)fs擴(kuò)展fs-extra說(shuō)明
這篇文章主要介紹了Node.js文件系統(tǒng)fs擴(kuò)展fs-extra說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08webpack創(chuàng)建項(xiàng)目并打包的詳細(xì)流程記錄
webpack在前端工程領(lǐng)域起到了中流砥柱的作用,理解它的內(nèi)部實(shí)現(xiàn)機(jī)制會(huì)對(duì)你的工程建設(shè)提供很大的幫助(不論是定制功能還是優(yōu)化打包),下面這篇文章主要給大家介紹了關(guān)于webpack創(chuàng)建項(xiàng)目并打包的詳細(xì)流程,需要的朋友可以參考下2023-03-03node.js中的fs.appendFileSync方法使用說(shuō)明
這篇文章主要介紹了node.js中的fs.appendFileSync方法使用說(shuō)明,本文介紹了fs.appendFileSync方法說(shuō)明、語(yǔ)法、接收參數(shù)、使用實(shí)例和實(shí)現(xiàn)源碼,需要的朋友可以參考下2014-12-12修改node.js默認(rèn)的npm安裝目錄實(shí)例
今天小編就為大家分享一篇修改node.js默認(rèn)的npm安裝目錄實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-05-05node.js中的buffer.fill方法使用說(shuō)明
這篇文章主要介紹了node.js中的buffer.fill方法使用說(shuō)明,本文介紹了buffer.fill的方法說(shuō)明、語(yǔ)法、接收參數(shù)、使用實(shí)例和實(shí)現(xiàn)源碼,需要的朋友可以參考下2014-12-12nodejs報(bào)digital?envelope?routines::unsupported錯(cuò)誤的最新解決方法
這篇文章主要介紹了nodejs報(bào)digital?envelope?routines::unsupported錯(cuò)誤的最新解決方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-02-02