首先还是先感谢github,感谢github上提供此段源码的作者。跟昨晚的来比今天的静态文件服务器有点点复杂些,可以学到很多新的东西。
仔细会发现这次的代码多了一个fs.stat函数和readstream对象的pipe函数,stat这个函数是用来获取文件信息。第一个参数是传入文件路径,第二个则是回调函数,回调函数的第二个参数stats的属性为文件的基本信息。pipe函数用于将这个可读流和destination目标可写流连接起来,传入这个流中的数据将会写入到destination流中。通过在必要时暂停和恢复流,来源流和目的流得以保持同步。
该静态文件服务器的改进点在于使用了last-modified和if-modified-since报文头,可以不必要给浏览器返回它已经存在的文件。顺便可以根据浏览器请求资源的压缩方式返回给资源进行gzip或者deflate压缩。
var port = 8000;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);var server = http.createserver(function(request, response) { response.setheader(server, node/v5); var pathname = url.parse(request.url).pathname; console.log(url =  + pathname); if (pathname.slice(-1) === /) {  pathname = pathname + config.welcome.file; } var realpath = __dirname + / + path.join(assets, path.normalize(pathname.replace(/\.\./g, ))); console.log(realpath =  + realpath); var pathhandle = function (realpath) {  fs.stat(realpath, function (err, stats) {   if (err) {    response.writehead(404, not found, {'content-type': 'text/plain'});    response.write(stats =  + stats);    response.write(this request url  + pathname +  was not found on this server.);    response.end();   } else {    if (stats.isdirectory()) {     realpath = path.join(realpath, /, config.welcome.file);     pathhandle(realpath);    } 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();     //设置last-modified     //服务器给浏览器返回文件最后一次修改时间last-modified     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-modified-since报文头     //日期相同表示该资源没有变化则返回304     //告诉浏览器该资源你已经有了,不需要再请求了     if (request.headers[ifmodifiedsince] && lastmodified == request.headers[ifmodifiedsince]) {      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(server runing at port:  + port + .);
expires字段声明了一个网页或url地址不再被浏览器缓存的时间,一旦超过了这个时间,浏览器都应该联系原始服务器。这里设置失效时间为1年。
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};
枚举各种资源的类型,可根据扩展名设置content-type。
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};
   
 
   