Created
February 10, 2024 19:21
-
-
Save MuhammadMinhaj/ee2c725c3fe4f1eb3c0dbb8a7f284356 to your computer and use it in GitHub Desktop.
This file contains hidden or 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'); | |
| 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