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");
});
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.
child_process.exec() : spawns a shell and runs a command within that shell, passing the stdout and stderr to a callback function when complete.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With