5

你能帮忙看看下面这个用 grunt 运行的 node 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

从节点子进程中检索值

4

1 回答 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

      }
    }
);
于 2012-12-19T20:31:37.090 回答