I'm trying to retrieve the complete output of a script called on a server (stdout + stderr).
But I do not succeed to retrieve a stdout + stderr merged string.
I tried to pass writable streams as described in the documentation.
It's working with a fs.createWriteStream:
test.sh
echo "Hello $1 I'm a stdout message"
echo "Hello $1 I'm a stderr message" 1>&2
main.js
const {execFileSync} = require("node:child_process");
const fs = require("fs");
let writableStream = fs.createWriteStream("out");
writableStream.on('open', function() {
execFileSync("./test.sh", ["UserName"], {stdio: ['ignore', writableStream, writableStream]});
});
But I cannot make it work to write it to a Buffer or directly get the output with .toString() (I'm using Duplex stream allowing Write and Read (https://nodejs.org/api/stream.html#types-of-streams)):
const {execFileSync} = require("node:child_process");
const stream = require("node:stream");
let duplexStream = stream.Duplex();
let buffer = Buffer.alloc(10000);
duplexStream.on('open', function() {
execFileSync("./test.sh", ["UserName"], {stdio: ['ignore', duplexStream, duplexStream]});
});
duplexStream.pipe(buffer);
console.log(buffer.toString());
Returning an error:
node:internal/streams/readable:680
dest.on('unpipe', onunpipe);
^
TypeError: dest.on is not a function
at Duplex.Readable.pipe (node:internal/streams/readable:680:8)
at Object.<anonymous> (/mnt/c/Users/-/Documents/temp/testRedirectStderr/main.js:9:14)
at Module._compile (node:internal/modules/cjs/loader:1105:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47
Is there any way to merge stdout and sderr (synchronously not just concatenated) without the use of a file ?