Haris Ejaz
Haris Ejaz

Reputation: 51

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

I am trying to execute a binary file in linux when an electron app is started. In development mode, everything is working properly, but when I build the app binary file (which is part of the app) is not executed.

Here is the code where I`m executing the binary file:

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();
  });
});

Upvotes: 1

Views: 521

Answers (1)

cachique
cachique

Reputation: 1271

Directory path ./ is relative to generated executable file once packaged.
You should use __dirname to fully qualify your binary path and make it relative to the calling file.

const path = require('path')

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

...

  const ls = exec(myexefilepath);

If you use asar file format to package your app, previous solution won't work.

Your options then are:

  • Copy binary to the same folder where the generated executable file is.
  • Use app.getPath( name ) to get a path to a special directory where you can put your binary. My choice being name: userData

Upvotes: 1

Related Questions