1

I'm trying to redirect the subprocess stderr to it's stdout with:

let buffer = execSync("echo hello 1>&2", {stdio : ["pipe","pipe", 1]});
console.log("Result: " + buffer.toString());

My goal is to retrieve "hello" inside my variable "buffer". In the documentation I see that it's possible to redirect the stderr: https://nodejs.org/api/child_process.html#child_process_options_stdio

So I tried at first to just pipe the stderr to the stdout (see code above) but I figured out that it redirect to the parent process stdout.

Resulting in the following output:

node .\main.js
hello
Result:

I tried to add a custom Buffer:

const {subprocess, execSync} = require("node:child_process");
let buff = Buffer.alloc(128);

execSync("echo hello 1>&2", {stdio : ["pipe",buff, buff]});
console.log("Result:" + buff.toString());

But the buffer stays empty:

node .\main.js
Result:

Is it possible to redirect the subprocess stderr to the subprocess stdout returned by execSync ? Or am I mandatory to use custom stream or spawnSync ?

1 Answers1

0

execSync returns the stdout of the executed command, irrespective of the stdio option. What you want to achieve can be done with the asynchronous exec:

child_process.exec("echo hello 1>&2", function(error, stdout, buffer){
  console.log("Result: " + buffer.toString());
});
Heiko Theißen
  • 12,807
  • 2
  • 7
  • 31