Search code examples
javascriptangularjsnode.jsresponsekill-process

Nodejs unable to kill external windows executable program executed by Node itself


I am hosting Node as a server locally to interact with hardware.

My web application then makes a request to Node to execute 2 executable, whichever executable returns a data first will Respond it back to my Web Application.

By doing so, it causes the other executable to still be running in the background waiting for response from the hardware.

I am unable to kill off that process either, I have to either manually stop Node and run it again or task kill that executable.

My code are below:

Node.JS

var exec = require('child_process').exec;    

app.get('/Page', function (req, res) {
    var Page = function () {
        var a = exec('F:/Example1.exe', function (err, data) {
            console.log(err);
            console.log(data);
            b.kill();
            if (!res.headersSent) {
                res.send(data);
            }
        });
        var b = exec('F:/Example2.exe', function (err, data) {
            console.log(err);
            console.log(data);
            a.kill();
            if (!res.headersSent) {
                res.send(data);
            }
        });
    }
    Page();
});

Apparently, even with the kill command, I am still unable to terminate the process.

I should let you guys know, I am also using AngularJS for my front-end.

I have sourced online for solution, however Google's results are all slowly turning purple.

Thank you so much for those who post their solution, please explain to me the details of the solution as well. I would really want to learn more.

Thank you so much.


Solution

  • The problem with exec is it will wait until the program has executed for it's callback to run.

    You can use spawn instead, then you have control over the process as it's running.

     var spawn = require('child_process').spawn;
    
     app.get('/Page', function(req, res) {
         var Page = function() {
             var a = spawn('F:/Example1.exe');
             var b = spawn('F:/Example2.exe');
             var aData = '',
                 bData = '';
             a.stdout.on('data', function(data) {
                 aData += data.toString();
             });
             b.stdout.on('data', function(data) {
                 bData += data.toString();
             });
             a.on('close', function() {
                 b.kill();
                 if (!res.headersSent) {
                     res.send(aData);
                 }
             });
             b.on('close', function() {
                 a.kill();
                 if (!res.headersSent) {
                     res.send(bData);
                 }
             });
         }
         Page();
     });