Do I need to import a node.js module to write to a file or is there some way to do it in-engine?
Create 2D games in JavaScript, made easier · By
basically to save game in html5 way is use localstorage
but if you need more(read/wring file), yeah you have to include node module using electron.
The simpliest way to save data is using localstorage, as @reopucino said.
I use this class definition for saving using it.
- For game data, I use a game instance where I manage all the game elements and game workflow (for this example you can use your own approach). In this implementation, I don't use the game data. Feel free of implementing game attribute as you want.
- This is a generic class with basic operations, so you can extend it for a more specific data management (scores, saved games., archievements...).
- If you want to use another system for managing data (a database, a file...) you could override these methods.
For example, if I want to store data using a web API, I could use the "fetch" library or an XMLHttpRequest instance for sending data in the implementation.
The main advantage of using a solution like this is the abstraction for managing saving and load data that is provided to other modules: They don't need to know how or where the data is saved or from where is loaded.
export default class Storage { constructor(game) { this.game = game; } load(key) { return localStorage.getItem(key); } save(key, value) { return localStorage.setItem(key, value); } add(key, item, value) { const entry = this.load(key); entry[item] = value; this.save(key, entry); } }
And remember: games created with pixelbox are, in fact, html5 applications, so you can use any code that you can use for a web client application.