get request with promise in nodejs
'use strict';
var get = function get(url) {
// return new pending promise
return new Promise(function (resolve, reject) {
// http, https
var lib = require(url.match(/^(https|http)/));
var request = lib.get(url, function (response) {
if (response.statusCode < 200 || response.statusCode > 299) {
reject(new Error('Failed to load page, status code: ' + response.statusCode));
}
var body = [];
response.on('data', function (chunk) {
return body.push(chunk);
});
// resolve promise
response.on('end', function () {
return resolve(body.join(''));
});
});
request.on('error', function (err) {
return reject(err);
});
});
};Written by Bruce Lim
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Nodejs
Authors
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#