184h4a
Last Updated: May 12, 2016
·
886
· b-rucel

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);
        });
    });
};