开发者

Node.js Gzip inflating - node-compress

I'm trying to pull a gzipped json file from http://api.discogs.com/release/339901.

I have https://github.com/waveto/node-compress installed and all works fine if I make a request to the Stack Overflow API, but once I try to request discogs I get an error.

Assertion failed: (ret != Z_STREAM_ERROR), function GunzipInflate, file ../compress.cc, line 271.
Abort trap: 6

Code:

    var options = {
        host: 'api.discogs.com',
        port: 80,
        path: '/re开发者_如何学JAVAlease/339901',
        headers: {
            "Accept-Encoding": "gzip"
        }
    };

    var options = {
        host: 'api.stackoverflow.com',
        port: 80,
        path: '/1.1/questions',
        headers: {
            "Accept-Encoding": "gzip"
        }
    }

    http.get(options, function(res){

        var body = [];
        var gunzip = new compress.Gunzip();
        gunzip.init();

        res.setEncoding('binary');

        res.on('data', function(chunk){
            body.push(gunzip.inflate(chunk, 'binary'));
        });

        res.on('end', function(){
            gunzip.end();
            callback(null, JSON.parse(body.join('')), response);
        });

        res.on('error', function(e){
            callback(e, null, response);
        });

    });



function callback(err, data, res) {
    if(err) {
        console.log(err);
    }
    else {
        res.end(JSON.stringify(data));
    }
}

Any ideas?

UPDATE:

Seems they were not sending it gzipped. Here is what I eventually used.

    var options = {
        host: 'api.discogs.com',
        port: 80,
        path: '/release/339901',
        headers: {
            "Accept-Encoding": "gzip"
        }
    };

    http.get(options, function(getRes){
        var body = "";

        getRes.on('data', function(chunk){
            body = body + chunk;
        });

        getRes.on('end', function(err, data){
            res.end(body);
        });
    });


It seems that api.discogs.com is not returning a gzip encoded response.

You should check the content-encoding header first:

if (res.headers['content-encoding'] === 'gzip') { ... }

Asking for a gzip encoded response ("Accept-Encoding": "gzip") doesn't guarantee it.

You can verify it this way:

console.log(JSON.stringify(res.headers));

res.on('data', function(chunk){
    console.log(chunk.toString());
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜