我改了一下CheckResourceBehavior.js可以支持静态文件缓存。需要的童鞋可以替换一下。代码如下:
var fs = require('fs');
var mime = require('mime');
var path = require("path");
/**
* 静态资源请求
* @return {[type]} [description]
*/
module.exports = Behavior(function () {
'use strict';
return {
options: {
'url_resource_on': false
},
run: function () {
if (!RESOURCE_PATH || !this.options.url_resource_on || !this.http.pathname) {
return false;
}
var pathname = this.http.pathname;
if (pathname.indexOf('/') === 0) {
pathname = pathname.substr(1);
}
var reg = C('url_resource_reg');
//通过正则判断是否是静态资源请求
if (!reg.test(pathname)) {
return false;
}
var file = RESOURCE_PATH + '/' + pathname;
var res = this.http.res;
var req = this.http.req;
fs.stat(file, function (err, stats) {
if (err) {
res.statusCode = 404;
res.end();
} else {
var contentType = mime.lookup(file);
var exp_maxage = C('expires_maxAge') || 30 * 24 * 3600;
var expires = new Date();
var lastModified = stats.mtime.toUTCString();
var ifModifiedSince = "If-Modified-Since".toLowerCase();
expires.setTime(expires.getTime() + exp_maxage * 1000);
res.setHeader('Content-Type', contentType|| "text/plain");
res.setHeader("Cache-Control", "max-age=" + exp_maxage);
res.setHeader("Expires", expires.toUTCString());
res.setHeader("Last-Modified", lastModified);
if (req.headers[ifModifiedSince] && lastModified == req.headers[ifModifiedSince]) {
//console.log(304, "Not Modified");
res.writeHead(304, "Not Modified");
res.end();
} else {
var fileStream = fs.createReadStream(file);
fileStream.pipe(res);
fileStream.on('end', function () {
res.end();
});
}
}
});
//返回一个pendding promise, 不让后续执行
return getDefer().promise;
}
};
});