Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs grunt child process callback function example

Would you kindly help with the following example of a node exec command run with grunt?

The echo command is executing, and hello-world.txt is created, but the grunt.log.writeln commands in the callback function aren't firing.

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

References:

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

Retrieving a value from a node child process

like image 811
user1354017 Avatar asked Dec 19 '12 16:12

user1354017


1 Answers

DOH! This is in the FAQ.

When using Gruntjs for async tasks, one must manually specify when the task completes. 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

For posterity, the above should thus look like this:

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

      }
    }
);
like image 57
user1354017 Avatar answered Nov 15 '22 04:11

user1354017