How to persist data in an Electron app?

前端 未结 9 1127
刺人心
刺人心 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: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;
      }
     }
    

提交回复
热议问题