feat: add fetch module to support getting web content

This commit is contained in:
Levi Yan
2024-07-11 11:31:29 +08:00
parent b65b954737
commit 22b24f1561

29
src/fetch.ts Normal file
View 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;