如何与Node.js Express压缩中间件打好?

我想使用一些中间件来修剪HTML标记之间的所有空格,并将所有其他空格合并为一个空格。 这是为了帮助CSS,因为white-space-collapse: discard; 是不是广泛可用(如果是的话),我不是其他解决方法的粉丝。 我现在用一种天真的方式很好,但是我希望它能和express.compress中间件搭配。

这是我的:

 module.exports = function trimmer() { function getSize(chunk) { return Buffer.isBuffer(chunk) ? chunk.length : Buffer.byteLength(chunk); } return function trimmer(req, res, next) { var end = res.end , write = res.write , isHtml ; res.on('header', function() { //res.removeHeader('Content-Length'); // another thing I've tried; don't entirely understand it though }); res.write = function(chunk, encoding) { var type = res.getHeader('Content-Type') || ''; isHtml = type.indexOf('text/html') >= 0; if (!isHtml) { write.apply(res, arguments); return; } var html = chunk .toString(encoding) .replace(/>\s+</g, '><') .replace(/\s{2,}/g, ' ') ; var buffer = new Buffer(html, encoding); try { res.setHeader('Content-Length', getSize(buffer)); } catch (ex) {} return write.call(res, buffer, encoding); }; next(); }; }; 

这样做很好,就像这样:

 app.configure(function() { app.use(trimmer()); // app.use(express.compress()); // till I uncomment this line... then it breaks app.use(express.favicon()); app.use('/images', express.static(images)); app.use('/scripts', express.static(scripts)); app.use(less({ src: pub, dest: tmp })); app.use(express.static(tmp)); app.use(express.static(views)); }); 

取消注释上面提到的行会导致与不能修改已经发送的报头有关的exception。 这很公平,我明白这一点。 我看着compress的源代码 ,这是一个高于我的头。 我必须做什么/ monkeypatch不踩compress的脚趾(反之亦然)?

你试过把app.use(trimmer());app.use(express.compress()); ? 当前写入的方式, trimmer将在响应被压缩后被调用; 切换顺序可以确保:(1)你不是试图修剪压缩的数据,(2)修剪的结果将被正确压缩。