Promisify NodeJS HTTP Module Get Request

Javascript or NodeJS HTTP(S) module’s functionality is fairly low-level. Most of the projects are using Axois or Request library to perform the HTTP Request nowadays. But how do you do this when you are not allowed to install these libraries but you need to pass the data back for an async function? (e.g Doing a technical screening test in the HackerRank)

Here is an example, how to promisify the Get Request in a quick and dirty way

const getResult = url => {
    return new Promise((resolve, reject) => {
        https.get(
            url,
            (response) => {
                let data = ""
                response.on('data', (chunk) => {
                    data += chunk;
                });
                response.on('end', status => {
                    console.log(response.statusCode);
                    if (response.statusCode == 200)
                        resolve(data);
                    // Handle other status , such as 302 if necessary
                        
                });
            }).on('error', err => {
                // HTTP 404 
                reject(new URIError("Not Found"));
        });
    });
}
A Polyglot Software Engineer and Technical Consultant who is interesting in technology, programming, sports and reading. He is living in Melbourne, Australia and original form Hong Kong.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.