Nodejs实现的一个静态服务器实例
参考cnodejs.org上面的静态服务器例子,写了下面的一个nodejs静态服务器例子,里面包含cache,压缩,贴代码如下:
/** *静态文件服务器测试例子 *User:xuwm *Date:13-5-17 *Time:上午8:38 *TochangethistemplateuseFile|Settings|FileTemplates. */ varport=3333; varhttp=require("http"); varurl=require("url"); varfs=require("fs"); varpath=require("path"); varmime=require("./mime").types; varconfig=require("./config"); varzlib=require("zlib"); //创建http服务端 varserver=http.createServer(function(request,response){ varobj=url.parse(request.url); response.setHeader("Server","Node/V8"); console.log(obj); varpathname=obj.pathname; if(pathname.slice(-1)==="/"){ pathname=pathname+config.Welcome.file; //默认取当前默认下的index.html } varrealPath=path.join("assets",path.normalize(pathname.replace(/\.\./g,""))); console.log(realPath); varpathHandle=function(realPath){ //用fs.stat方法获取文件 fs.stat(realPath,function(err,stats){ if(err){ response.writeHead(404,"notfound",{'Content-Type':'text/plain'}); response.write("therequest"+realPath+"isnotfound"); response.end(); }else{ if(stats.isDirectory()){ }else{ varext=path.extname(realPath); ext=ext?ext.slice(1):'unknown'; varcontentType=mime[ext]||"text/plain"; response.setHeader("Content-Type",contentType);
varlastModified=stats.mtime.toUTCString(); varifModifiedSince="If-Modified-Since".toLowerCase(); response.setHeader("Last-Modified",lastModified);
if(ext.match(config.Expires.fileMatch)){ varexpires=newDate(); 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,"NotModified"); response.end(); }else{ varraw=fs.createReadStream(realPath); varacceptEncoding=request.headers['accept-encoding']||""; varmatched=ext.match(config.Compress.match);
if(matched&&acceptEncoding.match(/\bgzip\b/)){ response.writeHead(200,"Ok",{'Content-Encoding':'gzip'}); raw.pipe(zlib.createGzip()).pipe(response); }elseif(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("httpserverruninport:"+port);