Created
August 10, 2023 12:28
-
-
Save CliffCrerar/dd728cc47b016a871d648100c984927e to your computer and use it in GitHub Desktop.
writing your own fetch function using node.js http
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
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