NodeJS parse process.stdout to a variable
You can't do it. Read @mattr's answer.
Instead, you can hook into the process.stdout.write
and get all the text printed to process.stdout
. I'm using the code below with my Node.js server.
global.serverLog = "";
process.stdout.write = (function(write) {
return function(string, encoding, fileDescriptor) {
global.serverLog += string;
write.apply(process.stdout, arguments);
};
})(process.stdout.write);
Note that you can do the same thing to process.stderr
, too.
A less confusing version of the above would be:
process.stdout._orig_write = process.stdout.write;
process.stdout.write = (data) => {
mylogger.write(data);
process.stdout._orig_write(data);
}
You are trying to use the Readable Stream API on a Writable Stream. Specifically, the process.stdout
stream is for writing to stdout not reading from stdout. What you are trying to do isn't possible, would create an infinite loop if it did work, and breaks the definition of what stdin and stdout are.