Okay so basically I'm trying to create a typing game that uses a JSON file as the database. I'm using Nodejs to manipulate the use of a .json file with the fs module. What I want to do is have a main.js which operates the website's appearance which will contain a table of high scores, and I also want a player.js which will run on the back-end which updates a JSON file containing each player's name and high score.
So I was experimenting with it. I learned the hard way that require() is a node function. I want main.js to call a function from player.js and send it parameters.
var playerArr = player.updatePlayers("Rain", 30);
I know this doesn't work but the updatePlayers() function written with node in player.js returns an array and I want to set it to playerArr within main.js.
require() comes up with an error in the browser because its not a part of vanilla Javascript and I know it has to be run on a node server.
Is there any way to do this? It's for a school project and I'd love to be able to implement Nodejs and JSON into it.
Okay so everything's working except one crucial thing... the array isn't being sent back to the browser. I decided to use routes from express:
app.get("/:name,:score", returnScoreboard);
function returnScoreboard(request, response){
let data = request.params;
playerArr = updatePlayers(data.name, data.score);
response.send(playerArr);
}
Now in my main.js, this is my code:
var playerArr;
var updatePlayer = new XMLHttpRequest();
updatePlayer.onreadystatechange = () => {
playerArr = this.responseText;
}
updatePlayer.open("GET", "/Moo,100", true);
updatePlayer.send();
console.log(playerArr);
And I can't seem to get a response from into the playerArr. The JSON file that I'm using is getting updated correctly with a new object every time ({"name":"Moo", "score":100}) but it's not being assigned to playerArr. Please help!