Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

331
Views
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

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

"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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!