【问题标题】:child_process.fork not starting an express server inside of packaged electron appchild_process.fork 没有在打包的电子应用程序内启动快速服务器
【发布时间】:2018-03-15 05:50:41
【问题描述】:

我有一个电子应用程序,我不仅需要为用户运行界面,还需要启动一个快速服务器,为通过网络连接的人提供文件。

如果我正常启动 electron 和 express 服务器,我一切正常,但我非常有信心,我需要服务器在不同的线程中运行,以避免界面缓慢甚至服务器出现问题。

为此,我尝试使用 child_process.fork 运行我的 express 服务器,并且当我使用 npm start 时它可以工作,但是当我使用 electron-builder 创建一个 .exe 时,安装的程序不会启动 express服务器。

我尝试使用以下命令立即运行我的服务器:

require('child_process').fork('app/server/mainServer.js')

我尝试了几处更改,在文件前面加上__dirnameprocess.resourcesPath,甚至硬编码生成的文件路径;更改 fork 选项以通过 cwd: __dirnamedetached: truestdio: 'ignore';甚至尝试将spawnprocess.execPath 一起使用,这也可以与npm start 一起使用,但打包时不会(它会不断打开我的应用程序的新实例,在你这样做之后似乎很明显)

注意:如果我不立即 fork 并要求服务器脚本,则使用 require('server/mainServer.js') 它适用于打包的应用程序,因此最可能的问题不是 express 本身。

注意2:我有asar: false来解决其他问题,所以这不是这里的问题解决者。

我建立了一个小 git 项目来展示我的问题:

https://github.com/victorivens05/electron-fork-error

我们将不胜感激。

【问题讨论】:

    标签: node.js express electron child-process


    【解决方案1】:

    在 Samuel Attard (https://github.com/MarshallOfSound) 的大力帮助下,我得以解决问题(他实际上为我解决了问题)

    正如他所说:

    the default electron app will launch the first file path provided to it
    so `electron path/to/thing` will work
    in a packaged state, that launch logic is not present
    it will always run the app you have packaged regardless of the CLI args passed to it
    you need to handle the argument manually yourself
    and launch that JS file if it's passed in as the 1st argument
    The first argument to fork simply calls `process.execPath` with the first
    argument being the path provided afaik
    The issue is that when packaged Electron apps don't automatically run the
    path provided to them
    they run the app that is packaged within them
    

    换句话说。 fork 实际上是 spawnprocess.execPath 一起执行并将 fork 的第一个参数作为第二个参数传递给 spawn。

    在打包的应用程序中发生的情况是 process.execPath 不是电子,而是打包的应用程序本身。因此,如果您尝试spawn,该应用程序将一遍又一遍地打开。

    所以,Samuel 的建议是这样实现的:

    if (process.argv[1] === '--start-server') {
       require('./server/mainServer.js')
       return
    }
    
    require('./local/mainLocal.js')
    require('child_process').spawn(process.execPath, ['--start-server'])
    

    这样,第一次执行打包的应用程序时,process.argv[1] 将为空,因此服务器不会启动。然后它将执行电子部分(在我的情况下为 mainLocal)并重新启动应用程序,但这次传递argv。下次应用启动时,它将启动服务器并停止执行,因此应用不会再次打开,因为从未到达 spawn。

    非常感谢塞缪尔。

    【讨论】:

      猜你喜欢
      • 2018-10-30
      • 1970-01-01
      • 2019-08-27
      • 2016-07-23
      • 2019-07-14
      • 2018-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多