Skip to content

Instantly share code, notes, and snippets.

@coolov
Last active September 18, 2019 23:27
Show Gist options
  • Save coolov/65fa6da6df9ac73e0e906ef408743325 to your computer and use it in GitHub Desktop.
Save coolov/65fa6da6df9ac73e0e906ef408743325 to your computer and use it in GitHub Desktop.
/*
mnmlst fetch implementation for node
list of options:
https://nodejs.org/api/http.html#http_http_request_url_options_callback
example:
```
let { body } = await get('https://dog.ceo/api/breeds/image/random');
let data = JSON.parse(body);
```
*/
const fetch = (url, options = {}) =>
new Promise((resolve, reject) => {
let opts = Object.assign(
{ method: 'GET' },
options,
require('url').parse(url)
);
let client =
opts.protocol === 'https:' ? require('https') : require('http');
let req = client.get(opts, res => {
let body = '';
res.setEncoding('utf8');
res.on('data', d => (body += d));
res.on('end', () =>
resolve({
body,
headers: res.headers,
statusCode: res.statusCode
})
);
});
req.on('error', reject);
req.end();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment