Search code examples
javascriptnode.jsprocessdiscord.jschild-process

BATCH: How can I close running batch file by the name using node.js


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);
});

Solution

  • 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