簡體   English   中英

如何與Node.js Express壓縮中間件配合使用?

[英]How do I play nice with Node.js Express compress middleware?

我想使用一些中間件來修剪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的腳趾(反之亦然)?

您是否嘗試過放置app.use(trimmer()); app.use(express.compress()); 響應被壓縮 ,將調用trimmer當前編寫的方式。 切換順序可確保(1)您不打算修剪壓縮數據,以及(2)修剪結果將被正確壓縮。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM