So methods in the child process module like spawn and exec are ways in which I can run another script, or command outside of node, from within a script. When doing so this child process will end up having it’s own process id, and is a way to go about doing some things in parallel in a node.js environment.
When launching such a process there might be some kind of condition in which I will want to kill the child process if it is the kind of process that will keep going otherwise. Luckily doing so is very easy I just need to use the kill method that is provided to the object that is returned when using a child process module method like spawn. So in this post I will be quickly going over the basics of killing a process in nodejs.
In this demo I will be using two scripts one is the usual index.js file, and the other I will be calling loop.js. The main index.js file will launch the loop.js file using the spawn method to call node, at which point loop.js will keep looping, logging to the console until it is killed by a condition in the main index.js file.
So the loop.js is a very simple script that will just log to the console every half second by making use of the setInterval core js method.
So in this demo loop.js does not do much of anything, but it could be some other kind of script that does some heavy lifting of some kind.
The main index.js file which I will be starting with node in the command line serves as a main process that will start the child process, and when needed, stop it as well.
So the spawn method will call node in the command line, and pass a single argument, which is the same as calling:
When called it will return an object, that I have referenced in the variable script. This object has methods that allow for me to define event handlers to work with the output of the process, and also to stop it by calling the kill method of this object.
So that is it for now when it comes to the kill method of a child process instance when using methods like spawn and exec in the built in node module. There is more to write about when it comes to this topic though when it comes to things like the process exit method of the process global. There are also maybe some things to be aware of that have to do with the operating systems that I might want to write scripts for when it comes to things like exit codes.