Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js detect a child process exit

I am working in node, as it happens via a visual studio code extension. I successfully create child processes and can terminate them on command. I am looking to run code when the process unexpectedly exits, this appears to be what the "exit" event is intended for, but I'm unclear on how to call it, this is the code I am working with, the process runs, but does not detect/log on exit, note that output.append is visual studio code specific version of console.log():

        child = exec('mycommand', {cwd: path}, 
        function (error, stdout, stderr) { 
            output.append('stdout: ' + stdout);
            output.append('stderr: ' + stderr);
            if (error !== null) {
                output.append('exec error: ' + error);
            }
        });

        child.stdout.on('data', function(data) {
            output.append(data.toString()); 
        });

Here's four things I have tried that do not work in logging on exit:

        child.process.on('exit', function(code) {
            output.append("Detected Crash");
        });

        child.on('exit', function(code) {
            output.append("Detected Crash");
        });

        child.stdout.on('exit', function () {
            output.append("Detected Crash");
        });

        child.stderr.on('exit', function () {
            output.append("Detected Crash");
        });
like image 543
edencorbin Avatar asked Jan 19 '16 16:01

edencorbin


People also ask

What does process exit do in node JS?

The process. exit() method is used to end the process which is running at the same time with an exit code in NodeJS. Parameter: This function accepts single parameter as mentioned above and described below: Code: It can be either 0 or 1.

What is Child_process spawn?

child_process.exec() : spawns a shell and runs a command within that shell, passing the stdout and stderr to a callback function when complete.

Which function exits from the current NodeJS process?

exit() Function: This function tells Node. js to end the process which is running at the same time with an exit code. By calling this function Node. js will force the current process that's running to exit as soon as possible.


1 Answers

Looking at the node.js source code for the child process module, the .exec() method does this itself:

child.addListener('close', exithandler);
child.addListener('error', errorhandler);

And, I think .on() is a shortcut for .addListener(), so you could also do:

child.on('close', exithandler);
child.on('error', errorhandler);
like image 67
jfriend00 Avatar answered Oct 23 '22 21:10

jfriend00