0

I want to know how can I close running batch file using Child process or anything in node.js

This is an example for exec in child process

const { exec, spawn } = require('child_process');
exec('my.bat', (err, stdout, stderr) => {
  if (err) {
    console.error(err);
    return;
  }
  console.log(stdout);
});
Dominik
  • 6,078
  • 8
  • 37
  • 61
Miljte
  • 3
  • 1

3 Answers3

1

In order to kill the spawned process when using 'child_process', you need to return the created ChildProcess reference, in this case by exec().

You can then kill the process using it's own API, ie. doing childProcess.kill().

Full example:

const { exec, spawn } = require('child_process');
const childProcess = exec('my.bat', (err, stdout, stderr) => {
  // explicitly kill the process
  childProcess.kill();

  if (err) {
    console.error(err);
    return;
  }
  console.log(stdout);
});

Find more details in the node.js docs

tmilar
  • 1,631
  • 15
  • 19
  • What if this commands like I type command: start it is start the bat file then i type stop command so how I make it stop ? CUZ this ^ is for the commands? thank you. – Miljte Feb 25 '21 at 21:25
1

If anyone is running into the issue that the batch file is not killable with .kill() or process.kill(processToKill.pid) or is starting another exe that is independent of the batch file, one solution that worked for me was to check the exe/process name I want to kill in the task manager and kill it with the (Windows) cmd command "taskkill /IM name.exe".
In code that looks like the following:

Executing the extra program (.bat, .exe, .lnk):

const systemprocess = require("child_process");
exampleVariable = systemprocess.exec("C:/ProgramData/Microsoft/Windows/Start Menu/Programs/Accessories/Snipping Tool.lnk", (err, stdout, stderr) => {
    if (err) {
        console.error(err);
        return;
    }
    console.log(stdout);
});

Killing the process:

systemprocess.exec(`taskkill /IM SnippingTool.exe`, (err, stdout, stderr) => { 
        if (err) {
            throw err
        }
        if (stdout) {
            console.log('stdout', stdout)
        }
        console.log('stderr', err)
    });

Though if you execute another exe with spawn you should be able to kill it with varaibleNameOfChildProcess.kill(); like @Kworz answer suggests.

0

Instead of using exec use spawn, you might be able te retreive the PID generated by the bat file execution. Call process.kill(PID) to kill the running bat file

var spawn = require('child_process').spawn;
var child = spawn('my.bat', {detached: true});
process.kill(child.pid);
Kworz
  • 26
  • 3
  • The PID change for the process when it is start like if i start process in process it is will change the PID – Miljte Feb 25 '21 at 21:26