如何执行一个.bat文件从node.js传递一些参数?
我使用node.js v4.4.4,我需要从node.js运行一个.bat
文件。
从我的节点应用程序的js文件的位置.bat可以使用命令行使用以下path(Window平台)运行:
'../src/util/buildscripts/build.bat --profile ../profiles/app.profile.js'
但是,当使用节点我不能运行它,没有具体的错误抛出。
我在这里做错了什么?
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); });
下面的脚本解决了我的问题,基本上我必须:
-
转换为绝对path引用.bat文件。
-
使用数组将parameter passing给.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