Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node: Read spawn stderr/stdout after quick exit event?

Tags:

node.js

spawn

I'm using Node's spawn to create a new process. Sometimes this process will exit very quickly with an error code and a message on stderr. It appears that stderr is getting lost in this quick turnaround. I've tried this:

    reader.stderr.on('data', function (buf) {
        console.log('stderr message: ' + buf);
    });

    reader.on('exit', function (code, signal) {
        console.log('Exit');
    });

Output:

   Exit
   stderr message: ERROR: Missing required option for command.

I also tried reading it in the exit listener, but no luck:

     reader.on('exit', function (code, signal) {
        console.log('Exit');
        console.log('stderr: ' + reader.stderr.read());
    });

Output:

    Exit
    stderr: null

So, it appears the problem is that the stderr output is too slow, and is late after the exit event where I need that information. How can I fix this?

like image 367
srlm Avatar asked Oct 19 '14 02:10

srlm


1 Answers

Taken from the child_process docs for exit:

Note that the child process stdio streams might still be open.

They then describe the close event:

This event is emitted when the stdio streams of a child process have all terminated. This is distinct from 'exit', since multiple processes might share the same stdio streams.

So it looks like you should be using close, not exit.

like image 112
loganfsmyth Avatar answered Oct 13 '22 05:10

loganfsmyth