Skip to content

Instantly share code, notes, and snippets.

@CliffCrerar
Created August 10, 2023 12:28
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 CliffCrerar/dd728cc47b016a871d648100c984927e to your computer and use it in GitHub Desktop.
Save CliffCrerar/dd728cc47b016a871d648100c984927e to your computer and use it in GitHub Desktop.
writing your own fetch function using node.js http
const https = require('https')
async function fetch(url) {
return new Promise((resolve, reject) => {
const request = https.get(url, { timeout: 1000 }, (res) => {
if (res.statusCode < 200 || res.statusCode > 299) {
return reject(new Error(`HTTP status code ${res.statusCode}`))
}
const body = []
res.on('data', (chunk) => body.push(chunk))
res.on('end', () => {
const resString = Buffer.concat(body).toString()
resolve(resString)
})
})
request.on('error', (err) => {
reject(err)
})
request.on('timeout', () => {
request.destroy()
reject(new Error('timed out'))
})
})
}
// credit: https://stackoverflow.com/users/3767398/matfax
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment