Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

node.js - How to use request or http module to read gzip page into a string

I found the request module in js cannot handle gzip or inflate format http response correctly.

for example:

request({url:'some url'}, function (error, response, body) {
   //if the content-encoding is gzip, the body param here contains binaries other than readable string. And even worse after you convert the body to buffer, u even can not gunzip it.
}

so I want to use the sample code in official docs.

var request = http.get({ host: 'izs.me',
                         path: '/',
                         port: 80,
                         headers: { 'accept-encoding': 'gzip,deflate' } });
request.on('response', function(response) {
  var output = fs.createWriteStream('izs.me_index.html');

  switch (response.headers['content-encoding']) {
    // or, just use zlib.createUnzip() to handle both cases
    case 'gzip':
      response.pipe(zlib.createGunzip()).pipe(output);
      break;
    case 'deflate':
      response.pipe(zlib.createInflate()).pipe(output);
      break;
    default:
      response.pipe(output);
      break;
  }
});

The problem is that the code is writing the webpage into a file, I hope it can write the page into a string, so that i can process the page. I could not find any class like 'StringStream'.

If anyone has any idea on this,it will be great.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Pipe the response to the gzip stream and use it as you would use the original response object.

var req = http.request(options, function(res) {
    var body = "";

    res.on('error', function(err) {
       next(err);
    });

    var output;
    if( res.headers['content-encoding'] == 'gzip' ) {
      var gzip = zlib.createGunzip();
      res.pipe(gzip);
      output = gzip;
    } else {
      output = res;
    }

    output.on('data', function (data) {
       data = data.toString('utf-8');
       body += data;
    });

    output.on('end', function() {
        return next(false, body);
    });
 });

req.on('error', function(err) {
   next(err);
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...