node.js - easy http requests with gzip/deflate compression


I'm trying to figure out how the best way to easily send HTTP/HTTPS requests and to handle gzip/deflate compressed responses along with cookies.

The best I found was which handles everything except compression. Is there a module or method that will do everything I ask?

If not, can I combine request and zlib in some manner? I tried to combine zlib and http.ServerRequest, and it failed miserably.


12/20/2013 11:04:16 AM

Accepted Answer

Note: as of 2019, request has gzip decompression built in. You can still decompress requests manually using the below method.

You can simply combine request and zlib with streams.

Here is an example assuming you have a server listening on port 8000 :

var request = require('request'), zlib = require('zlib');

var headers = {
    'Accept-Encoding': 'gzip'

request({url:'http://localhost:8000/', 'headers': headers})
    .pipe(zlib.createGunzip()) // unzip
    .pipe(process.stdout); // do whatever you want with the stream
1/29/2019 8:14:02 PM

For anyone coming across this in recent times, the request library supports gzip decompression out of the box now. Use as follows:

    { method: 'GET'
    , uri: ''
    , gzip: true
  , function (error, response, body) {
      // body is the decompressed response body
      console.log('server encoded the data as: ' + (response.headers['content-encoding'] || 'identity'))
      console.log('the decoded data is: ' + body)

From the github readme

gzip - If true, add an Accept-Encoding header to request compressed content encodings from the server (if not already present) and decode supported content encodings in the response. Note: Automatic decoding of the response content is performed on the body data returned through request (both through the request stream and passed to the callback function) but is not performed on the response stream (available from the response event) which is the unmodified http.IncomingMessage object which may contain compressed data. See example below.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow