Home > OS >  Run a command line from inside a JS function (using Electron.js)
Run a command line from inside a JS function (using Electron.js)

Time:10-26

I am using Electron to build a Point-Of-Sale application. At certain times in the program, I will need for the cash register to open. This can be done by putting ECHO>COM3 into the command prompt on my Windows computer or by opening a .bat file that holds that command. I was previously using PHP to open the file which worked but I'd like to not have to use PHP because it would then have to be installed and configured on each computer that I want to use the program on.

If I make a javascript function like this

function openCashDrawer(){

}

What can I put in the function to execute my one line of code? As simple as this sounds, I have scoured the web and tried soooo many things and nothing has worked. I think there is a way it can be done trough node.js but I don't know how that works.

I do have nodeIntegration: true set in my main.js file

this is my package.json file

{
  "name": "elec",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "start": "electron main.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "electron": "^15.3.0"
  }
}

CodePudding user response:

This can be achieved by executing a shell command in Node.js, to do this the exec() function can be used from the child_process module.

Importing child_process

In order to use Node modules with electrion, the node integration first needs to be enabled, along with the remote module, this can be set in the webPreferences as such:

webPreferences: {
    nodeIntegration: true,
    contextIsolation: false,
    enableRemoteModule: true
}

With the following code, you can execute a shell command and handle the response from the standard output if needed.

const { exec } = require("child_process");

function openCashDrawer() {
    exec("ECHO>COM3", (error, stdout, stderr) => {
    if (error) {
        console.log(`[ERROR] openCashDrawer: ${error.message}`);
        return;
    }
    
    if (stderr) {
        console.log(`[STDERROR] openCashDrawer: ${stderr}`);
        return;
    }

    console.log(`openCashDrawer: ${stdout}`); // Output response from the terminal
    });
}

Handling Insufficient Permission

Executing shell commands through Node.js requires elevation to execute with the correct permissions. On Windows, this is to be able to execute it as an administrator, the solution to this is to adjust the Node application to have the according permissions so that it can execute shell commands.

  • Related