简体   繁体   中英

NodeJS parse process.stdout to a variable

I am trying to read from stdout and put it to a variable in NodeJS. This is what I've tried:

process.stdout.on('data', function(data) {
    console.log(data.toString())
});

console.log('hello')

I expect it to output hello two times, but it only outputs it one time. Why is the callback not triggered? It works when using stdin..

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 .

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);
}

I'd suggest the following:

  1. Pipe stdout from the process to a duplexstream where you can create a readstream
  2. You parse the data, and then you can close it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM