Reputation: 11
I want to use child_process.spawn
to execute a windows exe file and catch it's output.
When I use command line to run a thirdparty exe file (says A.exe
), it will print some logs to the cmd window. Like this:
C:\> A.exe
some outputs...
some more outputs...
However, when I spawn it in node.js, using this
import childProcess from 'child_process';
const cp = childProcess.spawn('A.exe');
cp.stdout.on('data', data => console.log(`stdout: ${data}`));
cp.stderr.on('data', data => console.log(`stderr: ${data}`));
There is no outputs at all.
I think the outputs of A.exe
is not to the stdout (so I can never get data by listening stdout), but I don't know how it print logs when running from command line.
Any help would be greatly appreciated.
Upvotes: 1
Views: 4704
Reputation: 1
I know this question is quite old, but im answering because it could help someone else.
I developed a .exe based on a Python program with PyInstaller. I wasnt able to get the Stdout of my .exe, even though i could see the prints on the .exe terminal.
After adding a stdout.flush()
after every print()
, and the rebuilding my .exe, i was able to get the data from the spawned subprocess on Nodejs.
Upvotes: 0
Reputation: 395
On Unix-type operating systems (Unix, Linux, macOS) child_process.execFile()
can be more efficient because it does not spawn a shell. On Windows, however, .bat and .cmd files are not executable on their own without a terminal, and therefore cannot be launched using child_process.execFile()
. When running on Windows, .bat and .cmd files can be invoked using child_process.spawn() with the shell option set, with child_process.exec()
, or by spawning cmd.exe and passing the .bat or .cmd file as an argument (which is what the shell option and child_process.exec() do). In any case, if the script filename contains spaces it needs to be quoted.
// On Windows Only ...
const { spawn } = require('child_process');
const bat = spawn('cmd.exe', ['/c', 'my.bat']);
bat.stdout.on('data', (data) => {
console.log(data.toString());
});
bat.stderr.on('data', (data) => {
console.log(data.toString());
});
bat.on('exit', (code) => {
console.log(`Child exited with code ${code}`);
});
Upvotes: 1
Reputation: 30725
Maybe give this approach a go:
var childProcess = require('child_process');
childProcess.exec('A.exe', function(error, stdout, stderr) {
if (error != null) {
console.log('error occurred: ' + error);
} else {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
}
});
// OR
var cp = childProcess.spawn('A.exe');
cp.stdout.on('data', (data) => {
console.log('stdout: ' + data.toString());
});
cp.stderr.on('data', (data) => {
console.log('stderr: ' + data.toString());
});
Upvotes: 0