const request = require('request'); const URL = 'http://de.releases.ubuntu.com/xenial/ubuntu-16.04.3-desktop-amd64.iso'; const MAX_SIZE = 10 * 1024 * 1024
1 - If the response from the server is compressed by gzip, you must enable the gzip option. https://github.com/request/request#examples For backward compatibility, response compression is not supported by default. To accept gzip-compressed responses, set the gzip parameter to true.
request .get({ uri: URL, gzip: true }) .on('error', function (error) { //TODO: error handling console.error('ERROR::', error); }) .on('data', function (data) { // decompressed data console.log('Decompressed chunck Recived:' + data.length, ': Total downloaded:', total_bytes_read) total_bytes_read += data.length; if (total_bytes_read >= MAX_SIZE) { //TODO: handle exceeds max size event console.error("Request exceeds max size."); throw new Error('Request exceeds max size'); //stop } }) .on('response', function (response) { response.on('data', function (chunk) { //compressed data console.log('Compressed chunck Recived:' + chunk.length, ': Total downloaded:', total_bytes_read) }); }) .on('end', function () { console.log('Request completed! Total size downloaded:', total_bytes_read) });
NB: If the server does not compress the response, but you still use the gzip / unzip option, then the decompression fragment and the original fragment will be equal. Therefore, you can do a Limit check anyway (from an unpacked / compressed piece) However, if the response is compressed you should check the size limit of the unpacked fragment
2 - if the answer is not compressed, you do not need the gzip parameter to unpack
request .get(URL) .on('error', function (error) { //TODO: error handling console.error('ERROR::', error); }) .on('response', function (response) { response.on('data', function (chunk) { //compressed data console.log('Recived chunck:' + chunk.length, ': Total downloaded:', total_bytes_read) total_bytes_read += chunk.length; if (total_bytes_read >= MAX_SIZE) { //TODO: handle exceeds max size event console.error("Request as it exceds max size:") throw new Error('Request as it exceds max size'); } console.log("..."); }); }) .on('end', function () { console.log('Request completed! Total size downloaded:', total_bytes_read) });