Node.js detect a child process exit

edencorbin picture edencorbin · Jan 19, 2016 · Viewed 11k times · Source

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

Answer

jfriend00 picture jfriend00 · Jan 19, 2016

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