How To Use Electron's App.getpath() To Store Data?
I want to store images on the users computer, so I figure it should be stored in users data folder, as described here. app.getPath(name) name. Returns String - A path to a special
Solution 1:
Since the remote
method is being considered deprecated, as shown here, I'd suggest you do this:
const {app} = require('electron');
console.log(app.getPath('userData'));
Solution 2:
remote
is considered dangerous.
app.getPath
will be always available in main
process.
Here is how to do it in renderer process without using remote
(electron 7+)
Basically you have to use invoke
in renderer.
in main
ipcMain.handle('read-user-data', async (event, fileName) => {
const path = electron.app.getPath('userData');
const buf = await fs.promises.readFile(`${path}/${fileName));
return buf
})
in renderer
ipcRenderer.invoke('read-user-data', 'fileName.txt').then(result=>doSomething());
Solution 3:
Here is what I use when I need to switch between dev and release
const electron = require('electron');
exportconst userDataPath = (electron.app || electron.remote.app).getPath(
'userData'
);
Solution 4:
Another way to prevent the error "getPath is not a function" is to make the code work both in the renderer process and the main process:
const electron = require('electron');
const configDir = (electron.app || electron.remote.app).getPath('userData');
console.log(configDir);
Solution 5:
I had trouble with app.getPath('userData')
to save/load config files, etc and ended up using OS specific env vars in the meantime:
constgetAppBasePath = () => {
//devif (process.env.RUN_ENV === 'development') return'./'if (!process.platform || !['win32', 'darwin'].includes(process.platform)) {
console.error(`Unsupported OS: ${process.platform}`)
return'./'
}
//prodif (process.platform === 'darwin') {
console.log('Mac OS detected')
return`/Users/${process.env.USER}/Library/Application\ Support/${YOUR_APP_NAME}/`
} elseif (process.platform === 'win32') {
console.log('Windows OS detected')
return`${process.env.LOCALAPPDATA}\\${YOUR_APP_NAME}\\`
}
}
Post a Comment for "How To Use Electron's App.getpath() To Store Data?"