Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to REALLY kill a child_process nodejs

I'm using mocha with Nodejs to test my restApi. When I run mocha, I tell my test to create a child_process and run the API so I can make requests to it.

The problem is whenever the test exits (finishing or crashing), it seems that the API keeps running on background. I've seen some answers here that instructs 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 exits it does log "Killing child process", meaning that child.kill() was indeed called. But if I try to run my test again, when the spawn command gets called, the API throws an error

Error: listen EADDRINUSE :::3300

, meaning that the API is still running and that port address is taken.

So I have to run sudo pkill node to really kill all node process and then npm test works again.

Am I missing something? Is this really the way to achieve what I'm expecting?

I thought about using child_process.exec to run sudo pkill node on my process.on('exit') listener, but that doesnt seem like a smart thing to do.

This is happening both in Mac and Ubuntu.

Any suggestions? Thanks

like image 216
Thiago Loddi Avatar asked Apr 25 '17 14:04

Thiago Loddi


1 Answers

"exit" is an event that gets triggered when node finishes it's event loop internally, it's not triggered when you terminate the process externally.

What you're looking for is executing something on a SIGINT.

Have a look at http://nodejs.org/api/process.html#process_signal_events

like image 57
chrisandrews7 Avatar answered Nov 15 '22 05:11

chrisandrews7