Skip to content
Advertisement

Persistent file storage across electon app updates with electron-builder electron-updater

When I update an Electron app using the electron-builder autoUpdater, all the file storage I defined is overwritten. What settings do I need to make these files persist?

Here is an MCVE example (for the main process):

const { app, BrowserView, BrowserWindow,ipcMain } = require('electron');
const log = require("electron-log");
const { autoUpdater } = require("electron-updater");
const fs = require( 'fs');
const path = require('path');

let win
let rand = String(Math.floor(Math.random() * 10000));
console.log('Generated random number',rand)

app.whenReady().then(async () => {
  win = new BrowserWindow({
    fullscreen: false,
    webPreferences: {
      nodeIntegration: false,
      preload: path.join(__dirname, 'preload.js')
    }
  })
  win.loadFile('index.html');
  setInterval(function() {
    let a = autoUpdater.checkForUpdatesAndNotify();
  }, 60000);


  let exists = false;
  fs.stat('persistentFile',(err, stats) => {
      if (err == null){
        exists = true
      }
      if (!exists){
          fs.writeFile('persistentFile',rand,(err)=>{
            if (err) throw err;
            win.webContents.send('console_message', 'Persistent file has been created!',rand);
            console.log('Persistent file has been created!',rand);
          })
      }
      else {
          fs.readFile('persistentFile',(err,data)=>{
            if (err) throw err;
            win.webContents.send('console_message', 'Persistent already exists',data);
            console.log('Persistent already exists',data);
          })
      }
    })

  win.webContents.send('console_message', 'Random No is' + String(rand));


})

In this example I’d like the file persistentFile to persist across updates, so that it contains the number generated from the first version. However, at the moment, the file is overwritten every update.

How would you ensure persistent file storage across electron-builder autoupdates?

Advertisement

Answer

I managed to do this after looking at Cameron Nokes’ excellent blog:

cameronnokes.com/blog/how-to-store-user-data-in-electron:

Storing user data in the operating system’s designated location for user’s app data is the idiomatic way for native app’s to persist user data because:

  • when we auto-update the app, our source files may get moved or delete

  • changing or adding to an app’s internal files will invalidate the code signature

To do this I used const userDataPath = app.getPath('userData'); to get a path to the OS’ app storage location. and then changed the references to 'persistentFile' to String(userDataPath)+'/persistentFile':

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