run a windows batch file from node.js

前端 未结 4 1319
北恋
北恋 2020-12-05 15:58

am trying to run a test.bat file inside node.js

here is the code

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

case \'/start\':
    req.on(\'data         


        
相关标签:
4条回答
  • 2020-12-05 16:07

    The easiest way I know for execute that is following code :

    require('child_process').exec("path/to/your/file.bat", function (err, stdout, stderr) {
        if (err) {
            // Ooops.
            // console.log(stderr);
            return console.log(err);
        }
    
        // Done.
        console.log(stdout);
    });
    

    You could replace "path/to/your/file.bat" by __dirname + "/file.bat" if your file is in the directory of your current script for example.

    0 讨论(0)
  • 2020-12-05 16:09

    An easier way I know for executing that is the following code :

    function Process() {
    const process = require('child_process');   
    var ls = process.spawn('script.bat');
    ls.stdout.on('data', function (data) {
      console.log(data);
    });
    ls.stderr.on('data', function (data) {
      console.log(data);
    });
    ls.on('close', function (code) {
          if (code == 0)
            console.log('Stop');
          else
            console.log('Start');
    });
    };
    
    Process();
    
    0 讨论(0)
  • 2020-12-05 16:19

    I have found the solution for it.. and its works fine for me. This opens up a new command window and runs my main node JS in child process. You need not give full path of cmd.exe. I was making that mistake.

    var spawn = require('child_process').spawn,
    ls    = spawn('cmd.exe', ['/c', 'my.bat']);
    
    ls.stdout.on('data', function (data) {
    console.log('stdout: ' + data);
    });
    
    ls.stderr.on('data', function (data) {
    console.log('stderr: ' + data);
    });
    
    ls.on('exit', function (code) {
    console.log('child process exited with code ' + code);
    });
    
    0 讨论(0)
  • 2020-12-05 16:19

    In Windows, I don't prefer spawn as it creates a new cmd.exe and we have to pass the .bat or .cmd file as an argument. exec is a better option. Example below:

    Please note that in Windows you need to pass the path with double backslashes. E.g. C:\\path\\batfilename.bat

    const { exec } = require('child_process');
    exec("path", (err, stdout, stderr) => {
      if (err) {
        console.error(err);
        return;
      }
      console.log(stdout);
    });
    
    0 讨论(0)
提交回复
热议问题