从node.js运行Windows批处理文件

Sus*_*ush 12 batch-file node.js

我试图在node.js中运行test.bat文件

这是代码

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;
Run Code Online (Sandbox Code Playgroud)

正在运行此node.js文件

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

Sof*_*Guy 13

我找到了它的解决方案..它的工作对我来说很好.这将打开一个新的命令窗口,并在子进程中运行我的主节点JS.您无需提供cmd.exe的完整路径.我犯了那个错误.

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);
});
Run Code Online (Sandbox Code Playgroud)

  • 事实上,我可以确认这在Windows中可以执行`.bat`文件. (8认同)

Bru*_*eur 5

我知道的最简单的执行方法是以下代码:

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);
});
Run Code Online (Sandbox Code Playgroud)

例如"path/to/your/file.bat"__dirname + "/file.bat"如果您的文件在当前脚本的目录中,您可以替换为。


Pin*_*jee 5

在 Windows 中,我不喜欢 spawn,因为它会创建一个新的 cmd.exe,我们必须将 .bat 或 .cmd 文件作为参数传递。exec是更好的选择。下面的例子:

请注意,在 Windows 中,您需要使用双反斜杠传递路径。例如C:\\path\\batfilename.bat

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