在Grunt Task中运行一个命令

我在我的项目中使用Grunt (JavaScript项目的基于任务的命令行构build工具)。 我创build了一个自定义标签,我想知道是否可以运行一个命令。

澄清,我试图使用闭合模板和“任务”应该调用jar文件预编译大豆文件到一个JavaScript文件。

我从命令行运行这个jar,但我想把它设置为一个任务。

另外,你可以加载在grunt插件来帮助:

grunt-shell示例:

shell: { make_directory: { command: 'mkdir test' } } 

或者grunt-exec示例:

 exec: { remove_logs: { command: 'rm -f *.log' }, list_files: { command: 'ls -l **', stdout: true }, echo_grunt_version: { command: function(grunt) { return 'echo ' + grunt.version; }, stdout: true } } 

看看grunt.util.spawn

 grunt.util.spawn({ cmd: ['rm'], args: ['-rf', '/tmp'], }, function done() { grunt.log.ok('/tmp deleted'); }); 

我find了一个解决scheme,所以我想和你分享一下。

我正在节点下使用grunt,所以要调用terminal命令需要'child_process'模块。

例如,

 var myTerminal = require("child_process").exec, commandToBeExecuted = "sh myCommand.sh"; myTerminal(commandToBeExecuted, function(error, stdout, stderr) { if (!error) { //do something } }); 

如果你正在使用最新的grunt版本(写这篇文章的时候是0.4.0rc7),grunt-exec和grunt-shell都会失败(它们似乎没有被更新来处理最新的grunt)。 另一方面,child_process的exec是asynchronous的,这是一个麻烦。

我结束了使用Jake Trent的解决scheme ,并添加shelljs作为我的项目的开发依赖项,所以我可以轻松地同步运行testing:

 var shell = require('shelljs'); ... grunt.registerTask('jquery', "download jquery bundle", function() { shell.exec('wget http://jqueryui.com/download/jquery-ui-1.7.3.custom.zip'); }); 

伙计们指向child_process,但尝试使用execSync来查看输出..

 grunt.registerTask('test', '', function () { var exec = require('child_process').execSync; var result = exec("phpunit -c phpunit.xml", { encoding: 'utf8' }); grunt.log.writeln(result); }); 

对于使用Grunt 0.4.x的asynchronousshell命令,使用https://github.com/rma4ok/grunt-bg-shell