10

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?

JQuery Mobile
  • 6,221
  • 24
  • 81
  • 134

5 Answers5

6

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

Bruno
  • 898
  • 14
  • 17
  • Just one information about this in electron-json-storage. It use const os = require('os'); and storage.setDataPath(os.tmpdir()); But nothing others information about location in local app for example... – miltone Nov 22 '18 at 18:40
6

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!

Andrew Feldman
  • 107
  • 1
  • 8
  • When I used this approach, yes the file is written but the app resets and restarts due to an issue related to `nodemon` *https://github.com/remy/nodemon/issues/1509* – Vass Apr 15 '21 at 17:29
3

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);
    });
Ran Yitzhaki
  • 159
  • 1
  • 5
0

`const fs = require('fs');

let student = { 
    name: 'Mike',
    age: 23, 
    gender: 'Male',
    department: 'English',
    car: 'Honda' 
};
 
let data = JSON.stringify(student, null, 2);

fs.writeFile('student-3.json', data, (err) => {
    if (err) throw err;
    console.log('Data written to file');
});

console.log('This is after the write call');`
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-ask). – Community Sep 12 '21 at 22:44
0

There are multiple steps:
Step 1:
As of version 5, the default for nodeIntegration changed from true to false. You can enable it when creating the Browser Window:

const createWindow = () => {
  const win = new BrowserWindow({
     width: 1000,
     height: 800,
     webPreferences: {
       nodeIntegration: true,
       contextIsolation: false,
     }
  })
}

Step 2:

function writetofile() {
        let configsettings = {
          break: output.innerHTML,
          alwaysonoff: toggleoutput.innerHTML,
        };

        let settings_data = JSON.stringify(configsettings, null, 2);

        const fs = require("fs");

        fs.writeFileSync("assets/configs/settings.json", settings_data);
      }
gujaratiraja
  • 371
  • 2
  • 19