Created
November 30, 2022 07:23
-
-
Save aztack/056c76f4c960476cfd4feba194048928 to your computer and use it in GitHub Desktop.
https-fetch.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import https from 'https'; | |
function fetch(hostname: string, search: string) { | |
const options = { | |
hostname, | |
port: 443, | |
path: search, | |
method: 'GET', | |
}; | |
let buf = ''; | |
return new Promise((resolve, reject) => { | |
const req = https.request(options, res => { | |
res.on('data', d => { | |
buf += String(d); | |
}); | |
res.on('end', () => { | |
try { | |
resolve({ | |
text() { | |
return buf; | |
}, | |
json() { | |
return JSON.parse(buf); | |
} | |
}); | |
} catch (e) { | |
reject(JSON.stringify({ error: e })); | |
} | |
}); | |
}); | |
req.on('error', error => { | |
buf = JSON.stringify({ error }); | |
reject(buf); | |
}); | |
req.end(); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment