Last active
January 31, 2022 04:58
-
-
Save adamjarret/6d010d2bc22d072b4eaeeb906fff92a7 to your computer and use it in GitHub Desktop.
Node.js: Fetch and parse JSON content from a URL (no dependencies)
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
const { get } = require('https'); | |
function getJSON(url, options) { | |
return new Promise((resolve, reject) => { | |
get(url, options, (res) => { | |
let body = ''; | |
res.setEncoding('utf8'); | |
res.on('data', (data) => { | |
body += data; | |
}); | |
res.on('end', () => { | |
try { | |
resolve(JSON.parse(body)); | |
} catch (error) { | |
reject(error); | |
} | |
}); | |
}).on('error', reject); | |
}); | |
} | |
// Usage: | |
const obj = await getJSON('https://httpbin.org/get'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment