Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS HTTP Post - GZip

Tags:

node.js

I have a NodeJS client that is similar to

var options = {
  hostname: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST'
};

var req = http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

// write data to request body
req.write('data\n');
req.write('data\n');
req.end();

Is there any way to make the data element in the req.write gzipped at all?

like image 734
Lee Armstrong Avatar asked May 20 '14 00:05

Lee Armstrong


2 Answers

To send a compressed request, compress the data into a zlib buffer, then write that as your output:

var zlib = require('zlib');
var options = {
  hostname: 'www.example.com',
  port: 80,
  path: '/upload',
  method: 'POST',
  headers: {'Content-Encoding': 'gzip'} // signal server that the data is compressed
};
zlib.gzip('my data\ndata\n', function (err, buffer) {
    var req = http.request(options, function(res) {
        res.setEncoding('utf8');// note: not requesting or handling compressed response
        res.on('data', function (chunk) {
            // ... do stuff with returned data
        });
    });
    req.on('error', function(e) {
        console.log('problem with request: ' + e.message);
    });

    req.write(buffer); // send compressed data
    req.end();
});

That should send a gzipped request to the server and get a non-compressed response back. See the other answers to this question for handling a compressed response.

like image 170
Iain Ballard Avatar answered Oct 16 '22 18:10

Iain Ballard


You can gzip a stream using the native zip library: http://nodejs.org/api/zlib.html

like image 3
Paul Avatar answered Oct 16 '22 17:10

Paul