Skip to content

Instantly share code, notes, and snippets.

@snasirca
Created February 10, 2019 20:47
Show Gist options
  • Select an option

  • Save snasirca/fe1591c35ad4fe190f5c62ae5bd79234 to your computer and use it in GitHub Desktop.

Select an option

Save snasirca/fe1591c35ad4fe190f5c62ae5bd79234 to your computer and use it in GitHub Desktop.
Function for getting JSON data from endpoints using only built-in Node libraries
const { URL } = require('url')
const getJson = (url, options = {}) => new Promise((resolve, reject) => {
const urlParsed = new URL(url)
const lib = urlParsed.protocol === 'http' ? require('http') : require('https')
let optionsWithUrl = {
path: urlParsed.pathname + urlParsed.search,
host: urlParsed.hostname,
...options
}
const request = lib.get(optionsWithUrl, response => {
if (response.statusCode < 200 || response.statusCode > 299) {
reject(new Error('Request failed with status code: ' + response.statusCode))
}
const body = []
response.on('data', chunk => body.push(chunk))
response.on('error', err => reject(err))
response.on('end', function () {
const parsedBody = JSON.parse(body.join(''))
return resolve(parsedBody)
})
})
request.on('error', err => reject(err))
})
module.exports = getJson
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment