Skip to content

Instantly share code, notes, and snippets.

@hinchley
Created February 23, 2020 04:19
Show Gist options
  • Select an option

  • Save hinchley/6658fb58e968338bde364c95eeb3c82a to your computer and use it in GitHub Desktop.

Select an option

Save hinchley/6658fb58e968338bde364c95eeb3c82a to your computer and use it in GitHub Desktop.

Revisions

  1. hinchley created this gist Feb 23, 2020.
    45 changes: 45 additions & 0 deletions index.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,45 @@
    const fetch = (url, cb, options = {}) => {
    const { protocol } = new URL(url);

    const http = protocol === 'https:'
    ? require('https')
    : require('http');

    options = { headers: { 'User-Agent': 'node.js' }, ...options };

    const error = e => console.log(e.message);

    http.get(url, options, res => {
    const chunks = [];
    res.on('data', chunk => chunks.push(chunk));
    res.on('end', () => {
    const data = chunks.join('')
    try { cb(JSON.parse(data)); }
    catch (e) { cb(data); }
    });
    }).on('error', error);
    };

    const fetchp = async (url, options) => {
    return new Promise((resolve, reject) => {
    fetch(url, json => resolve(json), options);
    });
    };

    // callback syntax:
    fetch('https://api.github.com/users/hinchley', data => console.log(data));

    // http request:
    fetch('http://taco-randomizer.herokuapp.com/random/', data => console.log(data));

    // non-json response:
    fetch('https://google.com', data => console.log(data));

    // invalid request:
    fetch('https://invalid....com', data => console.log(data));

    // promisified version:
    (async () => {
    const data = await fetchp('https://api.github.com/users/hinchley');
    console.log(data);
    })();