Cannot capture stdout output of child process of batch script

Viewed 417

Using Node.js, I'm writing a Windows Batch script which calls some external programs. I want to execute this script and capture its output (and that of its children) to be able to display it inside an HTML container (I'm writing an Electron application). On Linux, I generate a Bash script that runs perfectly fine and whose output I can capture correctly. However, once the Windows Batch script spawns its child processes, I'm unable to capture their stdout and stderr; the only output child.stdout.on ("data", () => { /* ... */ }); catches is that of the Batch script itself.

I have tried various variants of how the Batch script calls the external programs, so far, neither has had the desired effect: all of them opened a new cmd.exe window. Using the advice from start /?, I am currently calling the programs as follows:

start /b /wait PROGRAM ARGUMENTS

(Where PROGRAM for example is pdflatex.exe.) By appending 2>&1 I was able to suppress new cmd.exe windows by running the batch script out of a cmd.exe window, but not by calling it from Node.js. I'm using the following code to call the Batch script:

const { spawn } = require ("child_process");
var child = spawn (
    "call",
    [ "path/to/batch.bat" ],
    {
        detached: true,
        shell: true
    }
);

Directly calling the Batch script by using the path to it as the command argument of spawn (); did not have the desired effect either.

Another method of invoking the Batch script and external programs I have tried but which did not have the desired result either, was to directly call the external programs from the Batch script like

C:\Full\Path\To\pdflatex.exe -halt-on-error -output-format=pdf file.tex

and using the Batch script's full path as the command argument to spawn (); like so:

const { spawn } = require ("child_process");
var child = spawn (
    "C:/Full/Path/To/Batch.bat",
    [  ],
    {
        detached: true,
        shell: true
    }
);

This did, like all other methods, capture the output of the cmd.exe process interpreting the script but opened a new cmd.exe window for all external programs called by the Batch script. The only other contents of the Batch script are along the lines of:

@echo off

REM Cd into the desired working directory
CD /D "C:\Path\To\Cwd"

REM Execute external programs like pdflatex:
C:\Full\Path\To\pdflatex.exe -halt-on-error -output-format=pdf file.tex

Nothing in the Batch script should actually interfere with how the commands are handled, but obviously this is not the case.

I am fine with modifying the call to spawn (); for Windows only; however, I must run the external programs using a Batch script and not using spawn (); directly because there is a requirement for backward compatibility I must meet.

So, after all, how would I be able to capture grandchild processes' stdout using a Batch script in Node.js?

0 Answers
Related