Skip to content
Advertisement

Saving JSON in Electron

I am building an app using Electron. In this app, I am building a data structure using JSON. My data structure looks like this:

{
  items: [
    { id:1, name:'football' },
    { id:2, name:'soccer ball' },
    { id:3, name:'basketball' }
  ]
}

I want to save this JSON to a file called “data.json”. I want to save it to a file because I want to load the next time the application starts. My challenge is, I do not know how to save the data. In fact, I’m not sure where I should even save the file. Do I save it in the same directory as the app? Or is there some cross-platform approach I should use?

Currently, I have the following:

saveClick: function() {
  var json = JSON.stringify(this.data);
  // assume json matches the JSON provided above.
  // Now, I'm not sure how to actually save the file.
} 

So, how / where do I save JSON to the local file system for use at a later time?

Advertisement

Answer

Electron lacks an easy way to persist and read user settings for your application. electron-json-storage implements an API somehow similar to localStorage to write and read JSON objects to/from the operating system application data directory, as defined by app.getPath('userData').

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement