1

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?

Oscar Q.
  • 65
  • 7
  • If you keep a reference to the child_process you can send it a kill signal from the "main" process using [`child_process.kill([signal])`](https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal). As a side note, why aren't you using [`child_process.fork(modulePath[, args][, options])`](https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options) since you're spawning another nodejs process? – Jake Holzinger Jul 15 '19 at 20:21

1 Answers1

1
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');
    }
}
Lennon McLean
  • 63
  • 1
  • 7