2

I'm attempting to run a simple batch file from my electron application. Here is my code:

globalShortcut.register('Control+B', () => { log.info('Batch File Triggered: ' + app.getAppPath() + '\\local\\print.bat') require('child_process').exec(app.getAppPath() + '\\local\\print.bat', function (err, stdout, stderr) { if (err) { // Ooops. // console.log(stderr); return console.log(err); } // Done. console.log(stdout); }); }) 

The batch file should be triggered when Control+B is pressed by the user, but it does not work. The log entry is made, and I've verified the path is correct, but the file is never actually launched.

I found these questions, which ask the same question, but these are 4 years old at this point and none of the answers have worked for me, there is no display, no error, nothing.

I've also tried the child_process.spawn but that also did nothing noticeable.

var ls = spawn('cmd.exe', ['/c', app.getAppPath() + '\\local\\print.bat']); 

How can I launch my batch file from my electron application?

2 Answers 2

11

I've just discovered such an easy way to do this. You can use the electron shell module, like this:

const {shell} = require('electron'); // Open a local file in the default app shell.openItem(app.getAppPath() + '\\local\\print.bat'); 
Sign up to request clarification or add additional context in comments.

1 Comment

This works great. Unfortunately, though, there doesn't appear to be a way to pass arguments with electron's shell.openItem. I found that although node's child_process.spawn can't be used to spawn node to run a file in the .asar, if I copy the file from the .asar and it's dependencies to somewhere else, I can spawn node and run it.
1

try using the code below

function Process() { const process = require('child_process'); var ls = process.spawn('script.bat'); ls.stdout.on('data', function (data) { console.log(data); }); ls.stderr.on('data', function (data) { console.log(data); }); ls.on('close', function (code) { if (code == 0) console.log('Stop'); else console.log('Start'); }); }; Process(); 

not forgetting to run

npm install child_process 

on your terminal

1 Comment

Are you able to pass arguments to the batch file with this?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.