gpt4 book ai didi

node.js - child_process.fork 没有在打包的 Electron 应用程序内启动快速服务器

转载 作者:IT老高 更新时间:2023-10-28 23:11:28 29 4
gpt4 key购买 nike

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

如果我正常启动 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

我们将不胜感激。

最佳答案

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

在打包的应用程序中发生的情况是 process.execPath 不是 Electron ,而是打包的应用程序本身。因此,如果您尝试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]为空,所以服务器不会启动。然后它将执行 Electron 部分(在我的例子中为 mainLocal)并重新启动应用程序,但这次传递 argv。下次应用启动时,它会启动服务器并停止执行,因此应用不会再次打开,因为从未到达 spawn。

非常感谢塞缪尔。

关于node.js - child_process.fork 没有在打包的 Electron 应用程序内启动快速服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46554634/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com