2

I want to load 2 json files:

number.json : {"argent":300,"nbJoueur":11,"nbClub":1,"nbVictoire":0,"nbDefaite":0}
img.json : {"bonus1":false,"bonus2":false,"bonus3":false,"bonus4":false,"bonus5":false,"bonus6":false}

I managed to read the first file, but I don't know what to do to read the second file in the same time.

I have this code :

Javascript :

function load(){
var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function(){

    if (this.readyState === 4 && this.status === 200){
        var recup = JSON.parse(this.responseText);
        number["argent"] = recup["argent"];
        number["nbJoueur"] = recup["nbJoueur"];
        number["nbClub"] = recup["nbClub"];
        number["nbVictoire"] = recup["nbVictoire"];
        number["nbDefaite"] = recup["nbDefaite"];           
    } 
};

xhr.open("GET","http://localhost:8080/load",true);
xhr.send();

}

Nodejs :

function load(response){
console.log("Load called");
fs.readFile("number.json", function(err,data){
    if(err) {
        throw err;
        response.setHeader("Access-Control-Allow-Origin","*");
        response.writeHead(418);
        response.end();
    }
    else{
        response.setHeader("Access-Control-Allow-Origin","*");
        response.writeHead(200);
        response.write(data);
        response.end();
    }
});

}

edkeveked
  • 17,989
  • 10
  • 55
  • 93
DakaYd0
  • 95
  • 1
  • 12

2 Answers2

1

Based on this answer, you can get your json file simply that way:

var json = require('path1.json'); 
var json2 = require('path2.json')

And then you can use the variables in your response callback

edkeveked
  • 17,989
  • 10
  • 55
  • 93
1

You've written a hardcoded handler that can only serve one file.

Instead, you could:

  • write a general handler that serves either file depending upon the url that's accessed.
  • Duplicate the load function and create a new path for the second file
  • Or, if your JSON files aren't going to change frequently, you can put them in a folder and serve it static

Edit: I noticed you aren't using any framework, so I removed my code sample that corresponds to the Express framework.