Last active
September 18, 2019 23:27
-
-
Save coolov/65fa6da6df9ac73e0e906ef408743325 to your computer and use it in GitHub Desktop.
This file contains 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
/* | |
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