Skip to content

Instantly share code, notes, and snippets.

@MuhammadMinhaj
Created February 10, 2024 19:21
Show Gist options
  • Save MuhammadMinhaj/ee2c725c3fe4f1eb3c0dbb8a7f284356 to your computer and use it in GitHub Desktop.
Save MuhammadMinhaj/ee2c725c3fe4f1eb3c0dbb8a7f284356 to your computer and use it in GitHub Desktop.
const https = require('https');
const { urlToHttpOptions } = require('url');
const nodeFetch = (url, options = {}) =>
new Promise((resolve, reject) => {
const _url = new URL(url);
const parsedOptions = urlToHttpOptions(_url);
const _options = { ...parsedOptions, ...options };
const request = https.request(_options, (response) => {
let data = '';
// A chunk of data has been received.
response.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received.
response.on('end', () => {
try {
const parsedData = JSON.parse(data);
resolve(parsedData);
} catch (error) {
reject(error);
}
});
});
// Handle errors.
request.on('error', (error) => {
reject(error);
});
// End the request to initiate the HTTP request.
request.end();
});
module.exports = nodeFetch;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment