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.

Revisions

  1. MuhammadMinhaj created this gist Feb 10, 2024.
    36 changes: 36 additions & 0 deletions node_fetch
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,36 @@
    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;