Oscar Q.
Oscar Q.

Reputation: 65

Terminate node.js script from another node.js script

I have a node.js script that runs another node.js script named 'app.js' using child_process.exec(). I need something that can terminate 'app.js'. Either a command that I can use in command line or something else in node.js.

I'm not trying to kill all node processes, only the process of 'app.js'. My computer is running Windows 10.

Right now the code looks like this:

let isLaunched = false;
const exec = require('child_process').exec;

function launch() {
    if (isLaunched) {
        isLaunched = false;

        // Something that terminates app.js

    } else {
        isLaunched = true;
        exec('node app.js');
    }
}

I call the function from a button in HTML.

<button onclick="launch()">Launch</button>

How can I do this in node.js?

Upvotes: 1

Views: 335

Answers (1)

Lennon McLean
Lennon McLean

Reputation: 326

var isLaunched = false;
var { exec } = require('child_process');
var myProcess; //use whatever name
function launch() {
    if (isLaunched) {
        isLaunched = false;
        myProcess.kill('SIGKILL');
    } else {
        isLaunched = true;
        myProcess = exec('node app.js');
    }
}

Upvotes: 1

Related Questions