Nodejs基于Express4的动态页面静态化( 二 )


ok,程序执行后静态页面就会带着动态数据生成到下的目录了;下面还是在.js()里将直指上面生成的静态页面;
1var pathname=url.parse(req.url).pathname;2var realpath='./public/famanoder/'+pathname.substr(pathname.lastIndexOf('/')+1)+'.html';3var type='text/html';4var extname='html';5fs.exists(realpath,function(exist){6if(!exist){console.log(101);7res.writeHead(404,{8'content-type':'text/plain'9});10res.write('The Resourse '+pathname+' was Not Found!');11res.end();12}else{13fs.readFile(realpath,'binary',function(err,file){14console.log(11);15if(err){16res.writeHead(500,{17'content-type':'text/plain'18});19res.end();20}21if(extname.match(config.fileMatch)){22var expires=new Date();23expires.setTime(expires.getTime()+config.maxAge*1000);24res.setHeader('Expires',expires.toUTCString());25res.setHeader('cache-control','max-age='+config.maxAge);26}27fs.stat(realpath,function(err,stat){28var lastModified=stat.mtime.toUTCString();29res.setHeader('Last-Modified',lastModified);3031if(req.headers['if-modified-since']&&lastModified==req.headers['if-modified-since']){32console.log(0);33res.writeHead(304,{34'content-type':type35});36res.end();37}else{38var raw=fs.createReadStream(realpath);39var acceptEncoding=req.headers['accept-encoding']||'';40var matched=extname.match(/css|js|html/ig);41if(matched&&acceptEncoding.match(/\bgzip\b/)){42console.log(1);43res.writeHead(200,{44'content-type':type,45'Content-Encoding':'gzip'46});47raw.pipe(zlib.createGzip()).pipe(res);48}else if(matched&&acceptEncoding.match(/\bdeflate\b/)){49console.log(2);50res.writeHead(200,{51'content-type':type,52'Content-Encoding':'deflate'53});54raw.pipe(zlib.createDeflate()).pipe(res);55}else{56console.log(3);57res.writeHead(200,{58'content-type':type59});60raw.pipe(res);61}62}63});64});65}66});
再次访问详情页 , 看看秒开了吧 , 纯静态的 , 路由没变 , url没改 , 维护也很简单 , 只要改下.templ.js就可以了;没办法啊 , 可能在大侠眼里这样很愚蠢 , 就当逗您一笑吧;类似这种搞法 , 现在小站全部页面都静态化了 , 而且完全照顾到了SEO;
好吧 , 其实还遗留了一个重要问题:就博客详情来说 , 原来如果有大批博客 , 现在怎么批量转呢 , 其实我是在博客编辑好后提交时顺便生成静态页面的 , 为了详情页再快点 。。。
;问题来了 , 在这之前如果我有几百上千篇博客(当然我这个小前端还远没达到这么丰硕的成果) , 我不得每篇博客重新编辑提交一次;吓死宝宝了啊 , 别急 , 新建一个.js直接批量生成吧 , 快的很!
1 Artical2.find({}).exec(function(err,docs) {3update(err,docs);4});5 6function update(err,docs) {7err&&console.log(err);8for(var i=0;i
其他牛逼启动更新的方式就不多讲了 , 
【Nodejs基于Express4的动态页面静态化】那么该轮到优化服务器和数据库了吧;好吧 。。。我后端渣渣 , 服务器更不谈了 , 暂且就这样吧 , 毕竟几十块钱的服务器;小前端刚学 , 诸多不足 , 望大侠路过指导