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?
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.
You can gzip a stream using the native zip library: http://nodejs.org/api/zlib.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With