-1

I am trying to make an online game and I am using JavaScript on repl.it and I want to save the player's high score when they lose. I have a file called high_scores.txt that is in the same directory as my script.js file, and I want to write the player's score in the file if it is higher than another score. I have been reading and it seems that you can't write files to other computers, but I am trying to write a file on the computer that is hosting the website. Does someone know how to do this?

Example: player's score = 145, files reads [563, 200, 76], this should write the player's score and make it [563, 200, 145] because it was bigger than that one

Or... player's score = 145, files reads [563, 200, 76], this should write the player's score and make it [563, 200, 76, 145]

I just need some way to read and write the file.

Shark Coding
  • 143
  • 1
  • 10

1 Answers1

1

It's not completely impossible (saving files, retrieving files), but it's extremely cumbersome.

For what you're trying to accomplish, it would be far easier to read and save Local Storage, which saves the data persistently through the user's browser:

const oldHighScores = JSON.parse(localStorage.highScores || '[]');
// ... get newScore
const newHighScores = [...oldHighScores, newScore].sort((a, b) => a - b).slice(1);
localStorage.highScores = JSON.stringify(newHighScores);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • will this allow other people to see your high scores, like, the file saves the top ten high scores out of everyone who has played? Because that is what I wanted – Shark Coding Nov 21 '20 at 23:43
  • 2
    For communication between clients like that, you'll need to set up server-side logic, like a database and routes. It can't be done purely from a browser's `.js`. – CertainPerformance Nov 21 '20 at 23:44