Daniel Stephens
Daniel Stephens

Reputation: 3209

Where do I execute my on-first-start functions in my Electron app?

I am using Electron 9 and I have a main process and a single render process. On the first start of my application I would like to execute some code which is not executed on the second run.

Does Electron have a dedicated location where I should do this? Any help is highly appreciated!

Upvotes: 3

Views: 2726

Answers (1)

sanperrier
sanperrier

Reputation: 634

  1. Use app.getPath('userData') - it's dedicated location for your apps data for current user (eg. in windows it will point to something like AppData/Roaming/app-name/)
  2. At startup use:
app.on('ready', () => {
  const firstTimeFilePath = path.resolve(app.getPath('userData'), '.first-time-huh');
  let isFirstTime;
  try {
    fs.closeSync(fs.openSync(firstTimeFilePath, 'wx'));
    isFirstTime = true;
  } catch(e) {
    if (e.code === 'EEXIST') {
      isFirstTime = false;
    } else {
      // something gone wrong
      throw e;
    }
  }

  // ...
});
  1. Profit!

https://nodejs.org/api/fs.html#fs_file_system_flags - why use wx flag https://nodejs.org/api/fs.html#fs_fs_opensync_path_flags_mode - fs.openSync() https://www.electronjs.org/docs/api/app#appgetpathname - app.getPath()

If you want to write out default preferences in the first run and read them in the next runs, try this:

import defaults from './default_preferences.json'; // will work for plain js objects too

let prefs = defaultPrefs;

app.on('ready', () => {
  const prefsPath = path.resolve(app.getPath('userData'), 'prefs.json');
  let isFirstTime;
  try {
    fs.writeFileSync(prefsPath, JSON.stringify(defaultPrefs), { flag: 'wx' });
    isFirstTime = true;
  } catch (e) {
    if (e.code === 'EEXIST') {
      // slight posibility of races, you can eleminate it by using `singleInstanceLock` or waiting loop for `write` flag
      prefs = require(prefsPath);
      isFirstTime = false;
    } else {
      // something gone wrong
      throw e;
    }
  }

  ...
});

Upvotes: 4

Related Questions