Skip to content

Instantly share code, notes, and snippets.

@valentinvieriu
Last active January 24, 2017 13:15
Show Gist options
  • Save valentinvieriu/d4fc5e41bce19c6aab0ba598d85d7ff4 to your computer and use it in GitHub Desktop.
Save valentinvieriu/d4fc5e41bce19c6aab0ba598d85d7ff4 to your computer and use it in GitHub Desktop.
const request = function request(reqUrl,options = {}) {
// parse url to chunks
reqUrl = url.parse(reqUrl);
// http.request settings
let settings = {
protocol: reqUrl.protocol,
host: reqUrl.hostname,
path: reqUrl.path,
port: reqUrl.port ? reqUrl.port : (reqUrl.protocol === 'https:' ? 443 : 80),
headers: {
'Accept-Encoding': 'gzip'
},
method: 'GET'
};
settings = Object.assign(settings,options);
// if there are params:
if (options.params) {
options.params = JSON.stringify(options.params);
settings.headers['Content-Type'] = 'application/json';
settings.headers['Content-Length'] = options.params.length;
};
// return new pending promise
return new Promise((resolve, reject) => {
// select http or https module, depending on reqested url
const libHttp = settings.protocol === 'https:' ? https: http;
const gunzip = require('zlib').createGunzip();
const httpRequest = libHttp.request(settings);
httpRequest.on('response', response => {
// handle http errors
if (response.statusCode < 200 || response.statusCode > 299) {
reject(new Error('Failed to load page, status code: ' + response.statusCode));
// consume response data to free up memory
response.resume();
return;
}
// temporary data holder
const body = [];
response.pipe(gunzip);
// on every content chunk, push it to the data array
gunzip.on('data', (chunk) => body.push(chunk));
// we are done, resolve promise with those joined chunks
gunzip.on('end', () => resolve(body.join('')));
gunzip.on('error', error => console.error(`ERROR=[gunzip]${error.message}`));
});
// handle connection errors of the request
httpRequest.on('error', err => reject(err))
// if there are params: write them to the request
if (options.params){
httpRequest.write(options.params)
};
//we need to call end
httpRequest.end();
})
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment