Daniel Tonon Daniel Tonon - 3 months ago 20
JSON Question

How to dynamically read external json files in node.js?

I am creating a website that reads externally hosted json files and then uses node.js to populate the sites content.

Just to demonstrate what I'm after, this is a really simplified version of what I'm trying to do in node.js

var ids = [111, 222, 333];

var json = getJSONsomehow('http://www.website.com/'+id+'.json');


I've managed to come close using the following code with this npm plugin: https://www.npmjs.com/package/xmlhttprequest

var XMLHttpRequest = require('xmlhttprequest');

function AJAX_JSON_Req( url ) {
var AJAX_req = new XMLHttpRequest.XMLHttpRequest();
AJAX_req.open( "GET", url, true );
AJAX_req.setRequestHeader("Content-type", "application/json");

return AJAX_req.responseText ;

It returns with an empty string though instead of the json data.

Is what I want to do possible?

(Marked as a duplicate of "How do I return the response from an asynchronous call?" see my comment below for my rebuttal)

rsp rsp

You are trying to get it synchronously. What you should aim for instead, is not a function used like this:

var json = getJSONsomehow('http://www.website.com/'+id+'.json');

but more like this:

getJSONsomehow('http://www.website.com/'+id+'.json', function (err, json) {
  if (err) {
    // error
  } else {
    // your json can be used here

or like this:

  .then(function (json) {
    // you can use your json here
  .catch(function (err) {
    // error

You can use the request module to get your data with something like this:

var request = require('request');
var url = 'http://www.website.com/'+id+'.json';

request.get({url: url, json: true}, (err, res, data) => {
  if (err) {
    // handle error
  } else if (res.statusCode === 200) {
    // you can use data here - already parsed as json
  } else {
    // response other than 200 OK

For a working example see this answer.

For more info see: https://www.npmjs.com/package/request