How to run a bat on click of button in NWJS app?

35 Views Asked by At

I cant figure out how to run a .bat file onclick of a button or input. Ive tried several different configurations.

The batch file is in the root directory of the nwjs application. Then once the batch is executed ill do various task on the system via CMD

<button id="run-button">Run Batch File</button>

const child_process = require('child_process');

// Define the path to the batch file
const batPath = 'F:/file.bat';

// Add an event listener to the button
document.getElementById('run-button').addEventListener('click', function() {
// Spawn a child process to run the batch file
const bat = child_process.spawn(batPath);

// Listen for any data from the child process
bat.stdout.on('data', function(data) {
// Print the data to the console
console.log(data.toString());
});

// Listen for any errors from the child process
bat.stderr.on('error', function(error) {
// Print the error to the console
console.error(error);
});

// Listen for the exit event of the child process
bat.on('exit', function(code) {
// Print the exit code to the console
console.log('Child process exited with code ' + code);
});
});
2

There are 2 best solutions below

0
sysrage On
const util = require('node:util');
const exec = util.promisify(require('node:child_process').exec);
const path = require('node:path');

async function runBat () {
    const batPath = path.resolve('./file.bat');
    const { stdout, stderr } = await exec(batPath);
    console.log('stdout', stdout);
    console.log('stderr', stderr);
}

document.querySelector('#run-button').addEventListener('click', runBat);

If this doesn't work, file.bat isn't in the current working directory. You can tweak the path.resolve() line to fix this (possibly using nw.App.startPath).

0
passThru On

How to use spawn at the click of a button...

var ch=require('child_process');

run_button.onclick=function(e){ 

  try{ ch.spawn('F:/file.bat',[],{}); } catch(e) {alert(e);}

};

I find JS error checking more practical than that of node.js

NB: I've changed your ID to run_button because you shouldn't use minuses (operators) in your identifiers.

Operators... + - * / % < > & ^ | ? =