【问题标题】:Electron - restart app / refresh environment variablesElectron - 重启应用程序/刷新环境变量
【发布时间】:2020-03-18 20:17:09
【问题描述】:

我目前正在开发一个使用第三方软件的 Electron 应用程序。在某些时候,我正在检查该软件是否安装在用户的计算机上(它必须在 PATH 中),如果它不存在,我就运行安装。正如我所说,安装会将一个目录附加到 PATH 变量中。发生这种情况后,我需要重新启动应用程序才能访问更新的变量。

我已经尝试使用relaunch,就像在文档中一样,但它不会刷新变量:

app.relaunch()
app.exit(0)

如果我手动重启应用程序,那么一切正常。

有人有什么想法吗?谢谢。

【问题讨论】:

  • 嗨@Alin,你找到解决这个问题的方法了吗?我也面临同样的问题。
  • 嗨,我找不到更新变量的解决方案,但现在我不再使用环境变量了...我使用文件的整个路径...那就是对我更好。
  • 在等待更好的解决方案时,我会要求我的用户在 Windows 下使用关闭按钮手动重启程序“使更改生效”。我想知道您是如何发现第三方库的完整路径的?我尝试使用which 包,但它使用`process.env.PATH` 来发现路径。
  • 就我而言,我已经知道 Windows 的路径,我只是将其硬编码在代码中。

标签: environment-variables electron


【解决方案1】:

我的解决方案只适用于生产:

在生产中,您的应用程序无法获取您 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,重新启动后应用程序将不会显示。我不知道。

【讨论】:

    猜你喜欢
    • 2018-09-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2021-06-27
    • 2016-04-16
    • 2015-08-28
    • 2016-08-12
    • 1970-01-01
    相关资源
    最近更新 更多