child_process.fork不打开包装电子应用程序内的快递服务器

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

如果我正常启动电子服务器和快速服务器,我都能正常工作,但是我非常有把握,我需要运行在不同线程中的服务器,以避免出现糟糕的界面甚至服务器问题。

对于这个问题,我尝试使用child_process.fork运行我的快递服务器,并且在使用npm start ,但是当我使用electron-builder创build一个.exe时,安装的程序不启动express服务器。

我试图立即运行我的服务器使用:

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

我尝试了几个改变,用__dirnameprocess.resourcesPath作为文件前缀,甚至对生成的文件path进行硬编码; 更改fork选项以传递cwd: __dirnamedetached: truestdio: 'ignore' ; 甚至尝试使用与process.execPath spawn ,这也将与npm start工作,但不会打包时(它不断打开我的应用程序的新实例,似乎很明显后,你做嘿嘿)

注意:如果我不需要fork,并且需要服务器脚本,使用require('server/mainServer.js')它可以在打包的应用程序上工作,所以最类似的问题不是require('server/mainServer.js')本身。

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

我build了一个小的git项目来显示我的问题:

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

任何帮助将不胜感激。

在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实际上是用process.execPath执行的,并且传递了fork的第一个参数作为产生的第二个参数。

打包的应用程序会发生什么情况, process.execPath不是电子的,而是打包的应用程序本身。 所以,如果你尝试spawn ,应用程序将一遍又一遍地打开。

所以,Samuelbuild议这样做:

 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 。 下一次应用程序启动,它将启动服务器,并停止执行,所以应用程序不会再次打开,因为从未到达的产卵。

非常感谢塞缪尔。