Saving JSON in Electron

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').


I wrote a simple library that you can use, with a simple interface, it also creates subdirectories and works with promises/callbacks. it will save the data into app.getPath("appData") as the root folder.

https://github.com/ran-y/electron-storage

Installation

$ npm install --save electron-storage

usage

const storage = require('electron-storage');

API

storage.get(filePath, (err, data) => {
  if (err) {
    console.error(err)
      } else {
        console.log(data);
      }
    });

storage.get(filePath)
    .then(data => {
      console.log(data);
    })
    .catch(err => {
      console.error(err);
    });

storage.set(filePath, data, (err) => {
      if (err) {
        console.error(err)
      }
    });

storage.set(filePath, data)
    .then(data => {
      console.log(data);
    })
    .catch(err => {
      console.error(err);
    });

Electron uses node.js as its core. You can use the following:

var fs = require("fs");
read_file = function(path){
     return fs.readFileSync(path, 'utf8');
}

write_file = function(path, output){
    fs.writeFileSync(path, output);
}

For write_file(), you can either pass "document.txt" as the path and it will write it to the same directory the html file it was run from. You can also put in a full path like "C:/Users/usern/document.txt" and it will write to the specific location you want.

Also, you can choose any file extention you want, (ie. ".txt", ".js", ".json", etc.). You can even make up your own!