如何将 gzip 流转换为可读内容并将其通过管道输出到请求中?

How to convert gzip stream into a readable content and pipe it out in the request?

我正在尝试对网站 (somesite.com) 进行代理调用并从中获取 html。 somesite.com 被丢弃并且被 zgipped 所以我无法将缓冲区(我的代码中的 responseFromServer)解析为 html(目前我在 res.write 时得到一堆乱七八糟的字符串)。 我尝试了 res.endres.send 但它们都不起作用。

 function renderProxyRequest(req, res) {
        // somesite.com is gzipped and also is chunked.
        var options = {
            protocol: 'http:',
            hostname: 'somesite.com',
            // passing in my current headers
            headers: req.headers,
            maxRedirects: 0,
            path: req.url,
            socketTimeout: 200000,
            connectTimeout: 1800,
            method: 'GET'
        }
        var proxyrequest = someProxyApi.request(options);
        proxyrequest.on('response', function (postresponse) {
            // postresponse is a buffer
            //postresponse.pipe(res);
            var responseFromServer = ''
            postresponse.on('data', function (data) {
                    responseFromServer += data;
            });
            postresponse.on('end', function () {
                // getting some jumbled string onto the browser.
                res.write(responseFromServer);
                res.end();
            })

        });
        req.pipe(proxyrequest);
    }

如果 postresponse 是一个流,您可以这样做:

const zlib = require('zlib');
...
postresponse.pipe(zlib.createGunzip()).pipe(res);

您必须首先通过检查来自远程服务器的 Content-Encoding header 来检查响应是否经过 gzip 压缩。

或者,如果您将原始 headers 从远程服务器传递到您代理请求的客户端,您应该能够只传递响应数据 as-is(因为原始的 headers 会告诉客户端数据已压缩)。这显然取决于客户端能够处理压缩响应(浏览器会)。