How to REALLY kill child_process nodejs
I am using mocha with Nodejs to test my restApi. When I run mocha I tell my test to build child_process
and run the API so I can make requests to it.
The problem is that when the test exits (exiting or failing), the API seems to keep running in the background. I saw several answers here that instruct to manually kill the child process whenever the main process exits. So I did it like this:
export function startProcess(done) {
const child = spawn('babel-node', ["app.js"]);
child.stdout.on("data", function(data) {
data = data.toString();
// console.log(data.toString());
if(data.indexOf("Server online") > -1) done();
});
child.stderr.on('data', function(err) {
console.log("ERROR: ", err.toString());
});
child.on('exit', function(code) {
console.log("PROPERLY EXITING");
console.log("Child process exited with code", code);
});
process.on('exit', function(code) {
console.log("Killing child process");
child.kill();
console.log("Main process exited with code", code);
});
}
When the main process finishes, it writes the "Killing child process" log, which means it was child.kill()
actually called. But if I try to run my test again when the spawn command is called, the API throws an error
Error: listening on EADDRINUSE: 3300
which means the API is still running and this port address is accepted.
So I need to start sudo pkill node
to actually kill the whole node process and then npm test
work again.
Am I missing something? Is this really the way to achieve what I expect?
I was thinking about using child_process.exec
to run sudo pkill node
in my listener process.on('exit')
, but that doesn't seem like a smart thing to do.
This happens on both Mac and Ubuntu.
Any suggestions? Thanks to
source to share
No one has answered this question yet
Check out similar questions: