Skip to content

Instantly share code, notes, and snippets.

@thybzi
Created November 20, 2019 11:43
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 thybzi/79f097e73647800bb3406fd4f23cb1d1 to your computer and use it in GitHub Desktop.
Save thybzi/79f097e73647800bb3406fd4f23cb1d1 to your computer and use it in GitHub Desktop.
/**
* @param {string} url
* @returns {Promise<string>}
* @private
*/
async function _fetchRemote(url) {
const http = /^https:/.test(url) ? require('https') : require('http');
return new Promise((resolve, reject) => {
http.get(url, res => {
res.setEncoding('utf8');
let body = '';
res.on('data', (data) => {
body += data;
});
res.on('end', () => {
resolve(body);
});
}).on('error', (err) => {
reject(err);
});
});
}
@thybzi
Copy link
Author

thybzi commented Nov 20, 2019

Usage (await):

const exampleBody = await _fetchRemote('http://example.com')
    .catch((ex) => { console.log(ex.message); });

Usage (promise):

let exampleBody;
_fetchRemote('http://example.com')
    .then((body) => { exampleBody = body; })
    .catch((ex) => { console.log(ex.message); });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment