在 electronJS 中创建父 window 时尝试 运行 二进制文件

Trying to run a binary file while creating parent window in electronJS

我正在尝试在启动 Electron 应用程序时在 linux 中执行二进制文件。在开发模式下,一切正常,但是当我构建应用程序二进制文件(它是应用程序的一部分)时,它没有被执行。

这是我执行二进制文件的代码:

const { spawn, exec } = require('child_process');
const startServer = () => {
  const ls = exec('./binary');
  ls.stdout.on('data', (data) => {
    console.log(`stdout: ${data}`);
  });
  ls.stderr.on('data', (data) => {
    console.error(`stderr: ${data}`);
  });
};

function createWindow() {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    icon: './electronJs.png',
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
    },
  });
  mainWindow.loadURL(
    url.format({
      pathname: path.join(__dirname, 'index.html'),
      protocol: 'file:',
      slashes: true,
    })
  );
}

app.whenReady().then(() => {
  createWindow();
  startServer();
  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

目录路径./是相对于打包后生成的可执行文件。
您应该使用 __dirname 来完全限定您的 binary 路径并使其相对于调用文件。

const path = require('path')

const myexefilepath = path.join(__dirname, 'binary')

...

  const ls = exec(myexefilepath);

如果您使用asar文件格式打包您的应用程序,之前的解决方案将不起作用。

你的选择是:

  • 复制binary到生成的可执行文件所在的文件夹。
  • 使用 app.getPath( name ) 获取一个特殊目录的路径,您可以在其中放置您的 binary。我的选择是 name: userData