代码之家  ›  专栏  ›  技术社区  ›  Victor Ivens

child_进程。fork未在打包的electron应用程序内启动express server

  •  15
  • Victor Ivens  · 技术社区  · 7 年前

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

    为此,我尝试使用child\u进程运行我的express服务器。叉子和它的工作时,我使用 npm start ,但当我使用 electron-builder 创建。exe,安装的程序不会启动express server。

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

    我尝试了几次更改,在文件前加上前缀 __dirname , process.resourcesPath cwd: __dirname , detached: true stdio: 'ignore' ; 甚至尝试使用 spawn process.execPath ,这也将与 npm启动

    注意:如果我没有立即分叉并需要服务器脚本,请使用 require('server/mainServer.js') 它在打包的应用程序上工作,所以最像的问题不是express本身。

    asar: false

    我提出了一个小git项目来说明我的问题:

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

    任何帮助都将不胜感激。

    1 回复  |  直到 7 年前
        1
  •  7
  •   Victor Ivens    7 年前

    在塞缪尔·阿塔德的大力帮助下( 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 实际上是 spawn process.execPath 并将fork的第一个参数作为第二个参数传递给spawn。

    打包应用程序中发生的情况是 过程执行路径 不是electron,而是打包的应用程序本身。所以如果你试着 产卵 ,应用程序将一次又一次打开。

    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] 将为空,因此服务器无法启动。然后,它将执行electron部分(在我的例子中是mainLocal)并重新启动应用程序,但这次通过了 argv

    非常感谢塞缪尔。