Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS parse process.stdout to a variable

Tags:

stream

node.js

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..

like image 439
user1506145 Avatar asked Oct 31 '14 12:10

user1506145


1 Answers

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.

like image 155
Константин Ван Avatar answered Oct 03 '22 10:10

Константин Ван