Created
November 1, 2016 06:55
-
-
Save kyptov/f0e754fd7465e8e2a2506781e909487a to your computer and use it in GitHub Desktop.
Simple function to request url using promise. Thanks to https://www.tomas-dvorak.cz/posts/nodejs-request-without-dependencies/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const getContent = function(url) { | |
return new Promise((resolve, reject) => { | |
// select http or https module, depending on reqested url | |
const lib = url.startsWith('https') ? require('https') : require('http'); | |
lib.get(url) | |
.on('response', resolve) | |
.on('error', reject); | |
}).then(response => { | |
return new Promise((resolve, reject) => { | |
// temporary data holder | |
const body = []; | |
// on every content chunk, push it to the data array | |
response.on('data', chunk => body.push(chunk)); | |
// we are done, resolve promise with those joined chunks | |
response.on('end', () => resolve(body.join(''))); | |
response.on('error', reject); | |
}); | |
}) | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment