Node.js Grunt 子进程回调函数示例

5

您能帮忙翻译一下使用grunt运行节点exec命令的示例吗?

echo 命令正在执行,创建了 hello-world.txt,但回调函数中的 grunt.log.writeln 命令没有触发。

var exec = require('child_process').exec,
    child;

    child = exec('echo hello, world! > hello-world.txt', 
        function(error, stdout, stderr){
            grunt.log.writeln('stdout: ' + stdout);
            grunt.log.writeln('stderr: ' + stderr);
            if (error !== null) {
                grunt.log.writeln('exec error: ' + error);
          }
        }
    );

参考资料:

http://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options

从Node子进程中检索值


那些东西在脚本中更靠前,而且运行良好。回调外的其他grunt writeln命令可以正确输出到控制台。module.exports = function (grunt) { grunt.registerTask('hello-world', '将“hello world”回显到文件中', function (srcpath, destpath) { - user1354017
那些繁琐的 grunt 日志注释可以等效地替换为 console.log() 命令。 - user1354017
1个回答

10

糟糕!这个问题已在常见问题解答中。

当使用Gruntjs进行异步任务时,必须手动指定任务何时完成。 https://github.com/gruntjs/grunt/wiki/Frequently-Asked-Questions
https://github.com/robdodson/async-grunt-tasks
https://github.com/rwldrn/dmv/blob/master/node_modules/grunt/docs/api_task.md

为了记录,上述内容应如下所示:

var exec = require('child_process').exec,
    child,
    done = grunt.task.current.async(); // Tells Grunt that an async task is complete

child = exec('echo hello, world! > hello-world.txt', 
    function(error, stdout, stderr){
        grunt.log.writeln('stdout: ' + stdout);
        grunt.log.writeln('stderr: ' + stderr);
        done(error); // Technique recommended on #grunt IRC channel. Tell Grunt asych function is finished. Pass error for logging; if operation completes successfully error will be null

      }
    }
);

请注意,done() 命令是使用三元运算符调用的,如果异步任务出现了一些问题,则通过该运算符将错误传递给它进行日志记录。请参阅 .message 属性。 - user1354017
更新上面的评论:已完成((错误)?错误:''); 技术从三元运算符更改为简单的done(error); 根据#grunt IRC频道的讨论。 - user1354017

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接