environment-variables - Electron - 重启应用程序/刷新环境变量
问题描述
我目前正在开发一个使用第三方软件的 Electron 应用程序。在某些时候,我正在检查该软件是否安装在用户的计算机上(它必须在 PATH 中),如果它不存在,我就运行安装。正如我所说,安装会将一个目录附加到 PATH 变量中。发生这种情况后,我需要重新启动应用程序才能访问更新的变量。
我已经尝试使用relaunch
,就像在文档中一样,但它不会刷新变量:
app.relaunch()
app.exit(0)
如果我手动重新启动应用程序,那么一切正常。
有人有什么想法吗?谢谢。
解决方案
我的解决方案只适用于生产:
在生产中,您的应用程序无法获取您 PC 的环境变量。因此,当您在 main.js 中创建 mainWindow 时,您应该读取环境变量并将其传递给 process.env 变量。重新启动应用程序后,它将按照您的预期再次重新加载 env。
正在使用的图书馆:
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();
}
// ...
}
重新启动应用程序后,环境变量将被更新。
app.relaunch()
app.exit(0)
注意:如果不勾选!isDevelopment
,重新启动后,应用程序将不会显示。我不知道。
推荐阅读
- python - pwntools python not importing
- c# - 业务层中的 TransactionScope 用于脏异步读取
- django-cms - django cms menu: display page title alongside the page's menu title
- react-native - APK 不会上传到 Fabric Crashlytics
- postgresql - 将包含十六进制字符串的文本编码为 utf-8
- django - 如何在 Django 中使用 LDAP 登录
- docker - 问题:如何在带有卷的 ARM 架构上的 Docker 上运行 TimeScaleDB?
- sql-server - 复制/粘贴、删除选项在 SQL Management Studio 中不起作用
- java - 设计模式如何在使用 List 时避免 instanceOf
- java - 用户 URLClassLoader “动态”加载 jar 文件