g运行t 运行 函数中的多个任务

grunt run multiple tasks in function

我正在使用 grunt-shell 和其他自定义任务。在我的任务中,我想 运行 逐步执行此任务并检查哪些任务 return。例如伪代码:

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函数,return没有任何回应或承诺。

您可以考虑使用 grunt-shell custom-callback 功能来捕获响应并处理任何条件逻辑。

以下示例 gist 当 运行ning $ grunt 通过您的命令行将执行以下操作:

  1. 将目录更改为项目根目录中名为 quux 的文件夹。如果名为 quux 的文件夹存在,将记录以下内容:

    Done: Successfully changed to directory 'quux'

  2. 但是,如果项目根目录中不存在名为 quux 的文件夹,将记录以下内容:

The folder named 'quux' is missing

  1. 随后 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']);
};