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

Gib*_*boK 12 javascript batch-file node.js

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

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

'../src/util/buildscripts/build.bat --profile ../profiles/app.profile.js'
Run Code Online (Sandbox Code Playgroud)

但是当使用节点我无法运行它时,不会抛出任何特定错误.

我在这做错了什么?


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

小智 15

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

var child_process = require('child_process');

child_process.exec('path_to_your_executables', function(error, stdout, stderr) {
    console.log(stdout);
});
Run Code Online (Sandbox Code Playgroud)


Gib*_*boK 13

以下脚本解决了我的问题,基本上我不得不:

  • 转换为.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);
    });
    
    Run Code Online (Sandbox Code Playgroud)

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

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