Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js execSync redirect stderr to stdout

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 ?

like image 406
Bytechie Avatar asked Sep 02 '26 09:09

Bytechie


1 Answers

I don't think you can read anything but the stdout with the execSync command, according to the documentation:

Returns: <Buffer> | <string> The stdout from the command.

So yes, you must use spawnSync. It will return an object with the property stderr, which contains a Buffer of the stderr output from the child process.

let buffer = spawnSync("my_subprocess").stderr;
console.log("Result: " + buffer.toString());
like image 183
JojoTheMAN21 Avatar answered Sep 03 '26 22:09

JojoTheMAN21



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!