'How to execute a Bash command using an Electron platform in Cordova

I'm trying to use Cordova that now includes Electron to create a Desktop App for Linux.

I want a button that fires a shell command:

const exec = require('child_process').exec

document.querySelector('button').onclick = () =>
  exec('ls -la', (err, stdout, stderr) => {
    console.log(stdout)
  })

Electron integrates Chromium with Node.js but deactivated by default in Cordova. After activating it, I'm getting the following error:

Uncaught ReferenceError: require is not defined

Note: this simple button click example is working fine with Electron Quick Example but when I try to do the same using Cordova + Electron require is not defined

Do I need to configure extra parameters and/or execute my index.js in a different scope?

Any help will be really appreciated :)



Solution 1:[1]

There is no direct method. It is only possible by using Electron without Cordova. You need to require the "child_process" in your Electron's main.js. Cordova produces this file automatically and may update it if you update the version. You can add the above codes manually to the "www\cdv-electron-main.js" and "platform_www\cdv-electron-main.js" or you can set a Cordova hook. for example, a before_run hook:

<platform name="electron">
    <hook type="before_run" src="hooks/beforeRun.js" />
</platform>

in your beforeRun.js file add this codes:

const fs = require('fs');
const util = require('util');
const path = require('path');

module.exports = function(ctx) {
    // Make sure electron platform is part of build
    if (!ctx.opts.platforms.includes('electron')) return;

    const platformRoot = path.join(ctx.opts.projectRoot, 'platforms/electron');
    
    const main1 = path.join(platformRoot, 'www/cdv-electron-main.js');
    const main2 = path.join(platformRoot, 'platform_www/cdv-electron-main.js');

    const extra = "const electron = require('child_process');" +
          "document.querySelector('button').onclick = () =>\n" +
               "  exec('ls -la', (err, stdout, stderr) => {\n" +
                                   "    console.log(stdout)\n" +
                                                         "  })";

    fs.appendFile(main1, extra, function (err) {
        if (err) throw err;
        console.log('Saved!');
    });
    fs.appendFile(main2, extra, function (err) {
        if (err) throw err;
        console.log('Saved!');
    });
};

this will add your const and on click function to the Electron's main JS files. You may need to clear before every run as the hook will add the above code to the end of the files multiple times. You can set a checker value to prevent this if you need it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SH DM