Created
February 10, 2019 20:47
-
-
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
This file contains hidden or 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
| 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