使用Express合并,缩小和提供JavaScript文件,但响应不是gzip压缩

 yuyiyin乐悠悠_964 发布于 2023-01-18 15:08

我正在使用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')));

问题是响应不是gzip压缩.此外,响应中有"无标题"(我的意思是,没有缓存标头,没有标签; static中间件提供的其他资源都有这些标头).这是回应:

X-Powered-By: Express
Transfer-Encoding: chunked
Date: Wed, 12 Mar 2014 14:04:19 GMT
Connection: keep-alive

我错过了什么吗?如何压缩响应?

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有