How do I execute a batch script on click of a button in NWJS app?

51 Views Asked by At

I have to execute a batch script on click of a button and I dont know where to begin. The batch scripts will do various different tasks for my nwjs application.

<input type="button" onclick="BatchFunc()"></button>
function BatchFunc() {
    code here
}

I tried this in various ways but got no success

function OpenTest() {
    nw.Shell.openItem('test.txt');
}

enter image description here

enter image description here

I tried this and when i click on the input it just shows a loading icon for a second then doesnt do anything else.

<script type="text/javascript">
            function runBatchFile () {
                const path = require('path');
                const executable = path.join('SOURCE CODE' , 'BATCH' , 'file.bat');
                const executableAndArgs = executable + ' --force --whatever';
                runExecutable(executableAndArgs, function (chunk) {
                    console.log({ chunk });
                });
            }
        </script>
2

There are 2 best solutions below

5
Jaredcheeda On
function runExecutable (executableAndArgs, callback) {
  const exec = require('child_process').exec;
  const child = exec(executableAndArgs, function (error, stdout, stderr) {
    console.log('stdout: ' + stdout);
    console.log('stderr: ' + stderr);
    if (error !== null) {
      console.log('Executable Error: ', error);
    }
  });
  // Return any text that was output to the console
  child.stdout.on('data', function (chunk) {
    if (typeof callback === 'function') {
      callback(chunk);
    }
  });
}
function runBatchFile () {
  const path = require('path');
  const executable = path.join('.', 'folder', 'file.bat');
  const executableAndArgs = executable + ' --force --whatever';
  runExecutable(executableAndArgs, function (chunk) {
    console.log({ chunk });
  });
}
<input type="button" onclick="runExecutable"></button>
4
sysrage On

A different take on Jared's suggestion:

const { promisify } = require('node:util');
const exec = promisify(require('node:child_process').exec);
const path = require('node:path');

async function runBatchFile (filePath) {
  const { stdout, stderr } = await exec(filePath);
  return { stdout, stderr };
}

const { stdout, stderr }= await runBatchFile(path.resolve('.', 'file.bat'));
console.log('stdout', stdout);
console.log('stderr', stderr);