How do I ungzip (decompress) a NodeJS request's module gzip response body?

前端 未结 9 1216
日久生厌
日久生厌 2020-11-27 04:21

How do I unzip a gzipped body in a request\'s module response?

I have tried several examples around the web but none of them appear to work.

request(         


        
9条回答
  •  被撕碎了的回忆
    2020-11-27 04:43

    I couldn't get request to work either, so ended up using http instead.

    var http = require("http"),
        zlib = require("zlib");
    
    function getGzipped(url, callback) {
        // buffer to store the streamed decompression
        var buffer = [];
    
        http.get(url, function(res) {
            // pipe the response into the gunzip to decompress
            var gunzip = zlib.createGunzip();            
            res.pipe(gunzip);
    
            gunzip.on('data', function(data) {
                // decompression chunk ready, add it to the buffer
                buffer.push(data.toString())
    
            }).on("end", function() {
                // response and decompression complete, join the buffer and return
                callback(null, buffer.join("")); 
    
            }).on("error", function(e) {
                callback(e);
            })
        }).on('error', function(e) {
            callback(e)
        });
    }
    
    getGzipped(url, function(err, data) {
       console.log(data);
    });
    

提交回复
热议问题