I'm currently working on an Electron app which uses a third party software. At some point I'm checking if that software is installed on the user's computer (it has to be in PATH), and if it's not there I just run the installation. As I said, the installation will append a directory to the PATH variable. After this happens, I need to restart the app in order to have access to the updated variables.
I already tried to use relaunch
, just as in the docs, but it doesn't refresh the variables:
app.relaunch()
app.exit(0)
If I restart the app manually, then everything works ok.
Does anyone have some ideas ? Thanks.
My solution just works for production:
In production, your application could not get your PC's environment variable. So, when you create mainWindow in main.js, you should read environment variables and pass it to process.env variable. After you relaunch the application, it will reload env again as you expected.
Library in use:
https://github.com/sindresorhus/shell-env
https://github.com/sindresorhus/shell-path
import shellEnv from 'shell-env';
import os from 'os';
import shellPath from 'shell-path';
const isDevelopment = process.env.NODE_ENV === 'development';
function createMainWindow() {
mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true,
},
width: 800,
height: 1000,
});
// ...
if (!isDevelopment) {
// TODO: if we're running from the app package, we won't have access to env vars
// normally loaded in a shell, so work around with the shell-env module
// TODO: get current os shell
const { shell } = os.userInfo();
const decoratedEnv = shellEnv.sync(shell);
process.env = { ...process.env, ...decoratedEnv };
console.log('DEBUG process.env', process.env);
// TODO: If we're running from the app package, we won't have access to env variable or PATH
// TODO: So we need to add shell-path to resolve problem
shellPath.sync();
}
// ...
}
After relaunching the application, the environment variables will be updated.
app.relaunch()
app.exit(0)
Notice: Without check !isDevelopment
, after relaunching, the application won't be displayed. I have no idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With