1

我想使用一些中间件来修剪 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));
});

取消注释上面提到的行会导致与无法修改已发送的标头相关的异常。这很公平,我明白这一点。我查看了compress源代码,这有点超出我的想象。我必须做什么/monkeypatch 才能不踩到compress's 脚趾(反之亦然)?

4

1 回答 1

2

你试过放app.use(trimmer());下面app.use(express.compress());吗?目前的写法,trimmer会在响应压缩后调用;切换顺序可确保 (1) 您不会尝试修剪压缩数据,以及 (2) 修剪的结果将被正确压缩。

于 2013-09-09T03:21:11.980 回答