Reputation: 3209
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
Reputation: 634
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/
)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;
}
}
// ...
});
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