【问题标题】:Closing Electron app does not stop the script关闭 Electron 应用程序不会停止脚本
【发布时间】:2020-09-07 06:38:42
【问题描述】:

我有一点问题希望有人能帮我解决。

我有一个 Electron + React 桌面应用程序,我需要正确处理它的关闭。 当我关闭应用程序(单击窗口上的 X)时,程序停止,但是,我用来运行程序的终端窗口并没有停止。

我使用这个脚本来运行程序:

npm run electron-dev

确实如此:

"scripts": {
   "start": "react-scripts start",
   "electron-dev": "concurrently \"npm run start\" \"wait-on http://localhost:3000 && electron .\""
 }

我正常运行我的应用程序,当我关闭窗口时,我的终端运行:

wait-on http://localhost:3000 && electron . exited with code 0

但我不能在终端上打字,除非我用 Control + C 杀死程序。

这是我处理应用关闭的方式:

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
     app.quit();
   }
});

app.on('before-quit', () => {
    mainWindow.removeAllListeners('close');
    mainWindow.close();
});

有人可以帮我解决这个问题吗?

【问题讨论】:

  • 你在什么平台上?
  • 我在多个平台上都遇到过这个问题,特别是 Windows 和 Linux

标签: javascript node.js reactjs npm electron


【解决方案1】:

这是因为您使用的是concurrently,这是预期的行为。

当您关闭窗口(并在 macOS 上退出程序)时,电子进程确实停止了,但是您在终端中给出的命令仍在运行,因为您仍在运行 react-scripts

查看您的electron-dev 脚本,您说您要运行命令npm startwait-on http://localhost:3000 && electron .\。当您关闭电子应用程序时,它会告诉您进程已结束 (wait-on http://localhost:3000 && electron . exited with code 0)。但是,您只结束了您创建的 2 个进程中的 1 个。创建npm start 的进程仍在运行,因此不会将终端控制返回给您。

npm start 执行命令react-scripts start,设置开发环境并启动服务器。你有a few options for killing the process,CTRL+C 是其中最简单的。

打包应用时不会出现此问题,当用户关闭窗口(或在 macOS 上退出程序)时应用会干净关闭

【讨论】:

  • 非常感谢,但有什么方法可以从应用程序内部关闭进程而不打包它?
  • 也许吧,但它真的很老套。你为什么要这样做?您可以使用 CTRL+C 来杀死终端中的两个进程。
【解决方案2】:

对于谁提出这个问题来说可能为时已晚,但对于仍在寻找解决方案的其他人来说:

你可以使用 npm-run-all。

这是package 的文档。

【讨论】:

    【解决方案3】:

    解决此问题的最优雅方法是在 concurrently 脚本中使用 --kill-others/-k 选项。

    在我的包文件中,在脚本下:

    "dev": "concurrently \"npm run client\" \"wait-on tcp:3000 && electron .\" -k",

    在相关进程的任何类型退出时,其他进程也会停止。这可以通过--kill-others-on-fail 进一步控制,如他们的文档中所述:

    https://www.npmjs.com/package/concurrently

    Killing other processes
      -k, --kill-others          kill other processes if one exits or dies [boolean]
          --kill-others-on-fail  kill other processes if one exits with non zero
                                 status code                               [boolean]
    

    【讨论】:

      猜你喜欢
      • 2015-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-27
      • 2018-07-17
      • 2013-05-13
      • 2013-08-03
      • 1970-01-01
      相关资源
      最近更新 更多