在步兵任务中运行命令

我在我的项目中使用 咕哝(JavaScript 项目中基于任务的命令行构建工具)。我已经创建了一个自定义标记,我想知道是否可以在其中运行一个命令。

为了澄清,我尝试使用闭包模板和“任务”应该调用 jar 文件预编译 Soy 文件到一个 javascript 文件。

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

70601 次浏览

I've found a solution so I'd like to share with you.

I'm using grunt under node so, to call terminal commands you need to require 'child_process' module.

For example,

var myTerminal = require("child_process").exec,
commandToBeExecuted = "sh myCommand.sh";


myTerminal(commandToBeExecuted, function(error, stdout, stderr) {
if (!error) {
//do something
}
});

Alternatively you could load in grunt plugins to help this:

grunt-shell example:

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

or grunt-exec example:

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
}
}

If you are using the latest grunt version (0.4.0rc7 at the time of this writing) both grunt-exec and grunt-shell fail (they don't seem to be updated to handle the latest grunt). On the other hand, child_process's exec is async, which is a hassle.

I ended up using Jake Trent's solution, and adding shelljs as a dev dependency on my project so I could just run tests easily and synchronously:

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');
});

Check out grunt.util.spawn:

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

For async shell commands working with Grunt 0.4.x use https://github.com/rma4ok/grunt-bg-shell.

Guys are pointing child_process, but try to use execSync to see output..

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