diff --git a/src/fetch.ts b/src/fetch.ts new file mode 100644 index 0000000..1b8809d --- /dev/null +++ b/src/fetch.ts @@ -0,0 +1,29 @@ +import * as http from 'http'; +import * as https from 'https'; + +function fetch(url: string): Promise { + // determine the library to use (based on the url protocol) + const lib = url.startsWith('https://') ? https : http; + + return new Promise((resolve, reject) => { + lib.get(url, (response) => { + // make sure the status code is 200 + if (response.statusCode !== 200) { + reject(new Error(`Failed to load page, status code: ${response.statusCode}`)); + return; + } + + let data = ''; + response.on('data', (chunk) => { + data += chunk; + }); + response.on('end', () => { + resolve(data); + }); + }).on('error', (err) => { + reject(err); + }); + }); +} + +export default fetch; \ No newline at end of file