How to persist data in an Electron app?

前端 未结 9 1129
刺人心
刺人心 2021-01-30 07:00

I\'ve been scouring the Electron documentation to try and figure out how to persist data in an Electron app. For example, in iOS or OS X, you could use NSUserDefaults to store u

相关标签:
9条回答
  • 2021-01-30 07:07

    There is a nice module for storing user data in elecron. It's called electron-store.

    Installation

    $ npm install electron-store
    

    Sample usage (copied from github page)

    const Store = require('electron-store');
    const store = new Store();
    
    store.set('unicorn', '                                                                    
    0 讨论(0)
  • 2021-01-30 07:10

    There is an NPM module I wrote called electron-json-storage that is meant to abstract this out and provide a nice and easy interface to the developer.

    The module internally reads/writes JSON to/from app.getPath('userData'):

    const storage = require('electron-json-storage');
    
    // Write
    storage.set('foobar', { foo: 'bar' }).then(function() {
    
        // Read
        storage.get('foobar').then(function(object) {
            console.log(object.foo);
            // will print "bar"
        });
    
    });
    
    0 讨论(0)
  • 2021-01-30 07:16

    You have multiple opions other than what mentioned in other answers.

    If you want to store data in an SQL databse then you can https://github.com/mapbox/node-sqlite3

    Or if you are storing configurations, You can store directly in OS's userData storage.

     const electron = require('electron');
     const fs = require('fs');
     const path = require('path');
    
     const dataPath = electron.app.getPath('userData');
     const filePath = path.join(dataPath, 'config.json');
    
     function writeData(key, value){
       let contents = parseData()
       contents[key] = value;
       fs.writeFileSync(filePath, JSON.stringify(contents));
     }
    
     function readData(key, value) {
      let contents = parseData()
      return contents[key]
     }
    
     function parseData(){
       const defaultData = {}
       try {
        return JSON.parse(fs.readFileSync(filePath));
      } catch(error) {
        return defaultData;
      }
     }
    
    0 讨论(0)
  • 2021-01-30 07:18

    There are a plethora of ways for data persistence that can be used in Electron and choosing the right approach depends essentially on your use case(s). If it's only about saving application settings then you can use simple mechanisms such as flat files or HTML5 Storage APIs, for advanced data requirements you should opt for large scale database solutions such as MySQL or MongoDB (with or without ORMs).

    You can check this list of methods/tools to persist data in Electron apps

    0 讨论(0)
  • 2021-01-30 07:21

    There is a module that gives simple methods to get and set json files to this directory, creates subdirectories if needed and supports callbacks and promises:

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

    Readme:

    Installation

    $ npm install --save electron-storage
    

    usage

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

    API

    storage.get(filePath, cb)

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

    storage.get(filePath)

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

    storage.set(filePath, data, cb)

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

    storage.set(filePath, data)

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

    storage.isPathExists(path, cb)

    storage.isPathExists(path, (itDoes) => {
      if (itDoes) {
        console.log('pathDoesExists !')
      }
    });
    

    storage.isPathExists(path)

    storage.isPathExists(path)
    .then(itDoes => {
      if (itDoes) {
        console.log('pathDoesExists !')
      }
    });
    
    0 讨论(0)
  • 2021-01-30 07:21

    You can go for Indexeddb, which is most likely suitable for client-side app needs due to:

    • Its built-in versioning mechanism. Client-side applications often face version fragmentation as users don't usually update to new version at the same time. So checking version of existing database and update accordingly is a good idea.
    • It's schemaless, which allows flexibility of adding more data to client's storage (which happen pretty often in my experience) without having to update database to a new version, unless you create new indices.
    • It support wide ranges of data: basic types as well as blob data (file, images)

    All in all it's a good choice. The only caveat is that chromium cores may automatically wipe out indexeddb to reclaim disk space when storage is under strain if navigator.storage.persist is not set, or when the host machine is crashed leaving indexeddb in corrupted state.

    0 讨论(0)
提交回复
热议问题