简体   繁体   中英

run a windows batch file from node.js

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', function (chunk) {});
    req.on('end', function () {
      console.log("INSIDE--------------------------------:");      
       exec('./uli.bat', function (err, data) {
        console.log(err);
        console.log(data);
        res.end(data);
      });
    });
    break;

while running this node.js file am getting

INSIDE--------------------------------:
{ [Error: Command failed: '.' is not recognized as an internal or ext
nd,
operable program or batch file.
] killed: false, code: 1, signal: null }

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

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.

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. Eg C:\\\\path\\\\batfilename.bat

const { exec } = require('child_process');
exec("path", (err, stdout, stderr) => {
  if (err) {
    console.error(err);
    return;
  }
  console.log(stdout);
});

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM