child_process.fork没有在打包的电子应用程序内启动快速服务器

Vic*_*ens 12 child-process node.js express electron

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

如果我正常启动电子和快速服务器,我的一切都在工作,但我非常有信心我需要在不同的线程中运行服务器,以避免棘手的接口,甚至服务器的问题.

为此,我尝试使用child_process.fork运行我的快速服务器,它在我使用npm start时工作,但是当我electron-builder用来创建.exe时,安装的程序不会启动快速服务器.

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

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

我尝试了几个更改,为文件添加前缀__dirname,process.resourcesPath甚至对生成的文件路径进行硬编码; 更改fork选项以通过cwd: __dirname,detached: truestdio: 'ignore'; 甚至尝试使用spawnwith process.execPath,它也可以使用npm start但不会在打包时(它会不断打开我的应用程序的新实例,看起来很明显)

注意:如果我不立即分叉并且需要服务器脚本,使用require('server/mainServer.js')它可以在打包的应用程序上运行,所以问题最不像快递本身.

注2:我必须asar: false解决其他问题,所以这不是解决问题的方法.

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

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

任何帮助将受到高度赞赏.

Vic*_*ens 5

从塞缪尔阿塔尔德有很大的帮助(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
Run Code Online (Sandbox Code Playgroud)

换一种说法.fork实际上spawn正在执行process.execPath并传递fork的第一个参数作为spawn的第二个参数.

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

所以,塞缪尔建议实施的是这样的:

if (process.argv[1] === '--start-server') {
   require('./server/mainServer.js')
   return
}

require('./local/mainLocal.js')
require('child_process').spawn(process.execPath, ['--start-server'])
Run Code Online (Sandbox Code Playgroud)

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

非常感谢塞缪尔.