I have the following exec command in a Node JS application that launches an EXE:
var exec = require('child_process').exec;
var theApp = 'HelloWorld';
var theCommand = 'C:/Program Files/' + theApp + '/dist/' + theApp + '-win32/' + theApp + '.exe';
exec(theCommand, function(error, stdout, stderr) {
console.log('command callback');
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
});
The EXE is launched fine, but none of the console logs are fired inside of the exec command, so it's as though calling an exe doesn't cause a callback to be fired. If I exec another Node app, e.g. node app.js
then it fires the callback! So it's because I'm calling an EXE to be opened!
How can I solve this?
When the program you are running starts up and does not terminate, you will not get any sort of callback or event until the program eventually exits. The system simply does not define any sort of event for that condition. A child process is either running or not. For any further detail about its condition, you are expected to communicate with it in some way (stdin, stdout, stderr, connect socket to it, interrogate the process in the system, etc...)
Since the program can literally be doing anything, all you can know from the outside is whether it exited quickly with an error or exited quickly with no error or whether it appears to be still running. The return value from the exec()
call contains a process ID so you can also query some info about that process ID if there's something specifically you want to know.
Here's an example of what you could do:
var exec = require('child_process').exec;
var theCommand = "notepad sample.txt";
function runit(cmd, timeout) {
return new Promise(function(resolve, reject) {
var ch = exec(theCommand, function(error, stdout, stderr) {
if (error) {
reject(error);
} else {
resolve("program exited without an error");
}
});
setTimeout(function() {
resolve("program still running");
}, timeout);
});
}
runit(theCommand, 1000).then(function(data) {
console.log("success: ", data);
}, function(err) {
console.log("fail: ", err);
});
It isn't clear to me which way you want it to act if the program you're running exits quickly, but without an error (the first call to resolve()
in the code). You could change that to a reject()
depending upon behavior what you want. I assumed that an exit without an error was not an error, but your situation might be different.
Note: if you aren't actually waiting for the completion of the other program, you may not want to use .exec()
since that is part of what it is built for. You may want to use one of the other child process creation methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With