feat: add fetch module to support getting web content
This commit is contained in:
29
src/fetch.ts
Normal file
29
src/fetch.ts
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
import * as http from 'http';
|
||||||
|
import * as https from 'https';
|
||||||
|
|
||||||
|
function fetch(url: string): Promise<string> {
|
||||||
|
// 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;
|
Reference in New Issue
Block a user