我正在使用Express构建一个web应用程序。我想要合并,缩小和服务.js文件。我编写了一个中间件,这是我的代码:
var fs = require('fs'),
path = require('path'),
uglify = require('uglify-js'),
cache = '',
scriptsDir = path.join(__dirname, '../scripts'),
files = fs.readdirSync(scriptsDir);
// Sync read is not a problem since the following code is executed on startup
files.forEach(function(fname) {
if (/^.*\.js$/.test(fname)) {
cache += fs.readFileSync(path.join(scriptsDir, fname), 'utf8').toString();
}
});
cache = uglify.minify(cache, { fromString: true }).code;
module.exports = function(req, res, next) {
if (req.url === '/js/all.js')
res.end(cache);
else
next();
};
中间件是这样使用的:
app.use(compress());
[...]
app.use(app.router);
app.use(jsMerger); // Here is my middleware
app.use(express.static(path.join(__dirname, '../public')));
问题是响应不是gzipped。此外,响应中也有“无头”(我的意思是,没有缓存头,没有etags;与static
中间件一起使用的其他资源都有这些头)。以下是我们的回应:
X-Powered-By: Express
Transfer-Encoding: chunked
Date: Wed, 12 Mar 2014 14:04:19 GMT
Connection: keep-alive
我是不是遗漏了什么?如何压缩响应?
发布于 2014-03-12 06:48:34
添加行后,res.set('Content-Type', 'text/javascript')
Express将对响应进行gzipping操作。代码是
module.exports = function(req, res, next) {
if (req.url === '/js/all.js') {
res.set('Content-Type', 'text/javascript');
res.end(cache);
} else {
next();
}
};
现在响应的标题是:
X-Powered-By: Express
Vary: Accept-Encoding
Transfer-Encoding: chunked
Date: Wed, 12 Mar 2014 14:45:45 GMT
Content-Type: text/javascript
Content-Encoding: gzip
Connection: keep-alive
原因在于compress
中间件是如何设计的。您可以向filter
提供compress
选项。
app.use(express.compress({
filter : function(req, res) {
return /json|text|javascript/.test(res.getHeader('Content-Type'));
}
});
压缩只应用于与筛选器匹配的请求。is的默认筛选器:
function(req, res){
return /json|text|javascript|dart|image\/svg\+xml|application\/x-font-ttf|application\/vnd\.ms-opentype|application\/vnd\.ms-fontobject/.test(res.getHeader('Content-Type'));
};
如果不提供Content-Type
头,请求将不会传递筛选器,而且express也不会将响应gzip。
https://stackoverflow.com/questions/22354264
复制