我正在使用grunt-shell和其他自定义任务。在我的任务中,我想逐步运行此任务并检查返回的任务。例如,伪代码:
grunt.task.registerTask('test', function () {
grunt.log.header('Running app');
var response = grunt.task.run('shell:go_to_folder');
if (response == 'folder not found') {
grunt.task.run('shell:create folder');
} else {
...
}
grunt.log.ok('Done');
});
但是grunt.task.run是
async
函数,并且没有返回任何响应或承诺。 最佳答案
您可以考虑使用grunt-shell
custom-callback功能来捕获响应并处理任何条件逻辑。
通过命令行运行$ grunt
时,以下示例gist将执行以下操作:
将目录更改为项目根目录中名为quux
的文件夹。如果名为quux
的文件夹存在,将记录以下内容:
Done: Successfully changed to directory 'quux'
但是,如果项目根目录中不存在名为quux
的文件夹,则会记录以下内容:
The folder named 'quux' is missing
随后,运行shell:create_folder
任务,在创建名为quux
的文件夹时,该日志将记录:
Successfully created folder named 'quux'
最后,运行shell:go_to_folder
任务,然后报告上面的点1。
Gruntfile.js
module.exports = function (grunt) {
'use strict';
grunt.loadNpmTasks('grunt-shell');
/**
* This callback is passed via the `go_to_folder` Task.
* If the folder named `quux` is missing it is reported to the Terminal
* and then invokes the `create_folder` Task.
* However, if the folder named `quux` does exists it reports successfully
* changing to the directory.
*/
function goToFolderCB(err, stdout, stderr, cb) {
// Check if the OS error reports the folder is missing:
// - `No such file or directory` is reported in MacOS (Darwin)
// - `The system cannot find the path specified` is reported in Windows cmd.exe
if (stderr && stderr.indexOf('No such file or directory') > -1
|| stderr.indexOf('The system cannot find the path specified') > -1) {
grunt.log.writeln('The folder named \'quux\' is missing');
grunt.task.run('shell:create_folder');
} else {
grunt.log.ok('Done: Successfully changed to directory \'quux\'');
}
cb();
}
/**
* This callback is passed via the `create_folder` task.
* After reporting successfully creating the folder named `quux`
* it runs the `go_to_folder` Task.
*/
function createFolderCB(err, stdout, stderr, cb) {
grunt.log.writeln('Successfully created folder named \'quux\'');
grunt.task.run('shell:go_to_folder');
cb();
}
grunt.initConfig({
shell: {
go_to_folder: {
command: 'cd quux',
options: {
stderr: false, // Prevent stderr logs in Terminal.
callback: goToFolderCB
}
},
create_folder: {
command: 'mkdir quux',
options: {
callback: createFolderCB
}
}
}
});
grunt.task.registerTask('test', function () {
grunt.log.header('Running app');
grunt.task.run('shell:go_to_folder');
});
grunt.registerTask('default', ['test']);
};