Home > Mobile >  How to Read / Write / Edit Files with Javascript
How to Read / Write / Edit Files with Javascript

Time:05-07

I want to create a game that saves your progress using files. Is it possible to do something along the lines of this pseudo-code?

/*game_data = The game's content*/
function saveGame () {
    create_file(game_data, "your-game-progress.txt")
}
function loadGame () {
    game_data = load_file("your-game-progress.txt")
}

Is there any way to accomplish this, with or without external libraries?

CodePudding user response:

Are you using a framework like React or NextJS? If so, there are several options for flat-file storage.

If you're using vanilla JS, your only real option for client-side storage is the localStorage() method.

/*game_data = The game's content*/
var game_data = {
   "player_name": "Joe",
   "experience": 4347873,
   "level": 10,
   "HP": 255
};

function saveGame () {
    localStorage.setItem('game_data', game_data);
    //create_file(game_data, "your-game-progress.txt")
}
function loadGame () {
    game_data = localStorage.getItem('game_data');
    //game_data = load_file("your-game-progress.txt")
}

function deleteGame() {
    localStorage.removeItem('game_data');
    /* OR */
    localStorage.clear(); // clears all local storage items
}

The problem, however, is the game data will be lost when the cookie expires or the user clears their cookies or uses a different browser. You might want to consider a server-side solution.

  • Related