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

child_process.fork not starting an express server inside of packaged electron app

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

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

就此而言,我尝试使用 child_process.fork 运行 我的快速服务器,当我使用 npm start 时它起作用了,但是当我使用 electron-builder 创建一个.exe,安装的程序没有启动快递服务器。

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

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

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

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

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

我放了一个小 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 实际上是 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。

非常感谢塞缪尔。