Last Updated: May 12, 2016
·
2.004K
· 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);
        });
    });
};

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
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