如何从node.js中执行一个传递一些参数的.bat文件

How to execute a .bat file from node.js passing some parameters?

本文关键字:一个 参数 文件 bat node js 执行      更新时间:2024-06-14

我使用node.js v4.4.4,需要从node.js.运行一个.bat文件

从我的节点应用程序的js文件的位置,.bat可以使用命令行运行,路径如下(窗口平台):

'../src/util/buildscripts/build.bat --profile ../profiles/app.profile.js'

但当使用node时,我无法运行它,不会抛出任何特定的错误。

我在这里做错了什么?


    var ls = spawn('cmd.exe', ['../src/util/buildscripts', 'build.bat', '--profile ../profiles/app.profile.js']);
    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);
    });

您应该能够运行这样的命令:

var child_process = require('child_process');
child_process.exec('path_to_your_executables', function(error, stdout, stderr) {
    console.log(stdout);
});

下面的脚本解决了我的问题,基本上我必须:

  • 转换为.bat文件的绝对路径引用。

  • 使用数组将参数传递给.bat。

    var bat = require.resolve('../src/util/buildscripts/build.bat');
    var profile = require.resolve('../profiles/app.profile.js');
    var ls = spawn(bat, ['--profile', profile]);
    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);
    });
    

以下是有用的相关文章列表:

https://nodejs.org/api/child_process.html#child_process_asynchronous_process_creation

https://nodejs.org/api/child_process.html#child_process_spawning_bat_and_cmd_files_on_windows

http://www.informit.com/articles/article.aspx?p=2266928