Skip to content

Instantly share code, notes, and snippets.

@adamjarret
Last active January 31, 2022 04:58
Show Gist options
  • Save adamjarret/6d010d2bc22d072b4eaeeb906fff92a7 to your computer and use it in GitHub Desktop.
Save adamjarret/6d010d2bc22d072b4eaeeb906fff92a7 to your computer and use it in GitHub Desktop.
Node.js: Fetch and parse JSON content from a URL (no dependencies)
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