Skip to content

Instantly share code, notes, and snippets.

@kyptov
Created November 1, 2016 06:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kyptov/f0e754fd7465e8e2a2506781e909487a to your computer and use it in GitHub Desktop.
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/
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