nodejs grunt child process callback function example
Asked Answered
R

1

5

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

Residency answered 19/12, 2012 at 16:57 Comment(2)
That stuff is further up in the script, and works fine. Other grunt writeln commands outside of a callback properly write to the console module.exports = function (grunt) { grunt.registerTask('hello-world', 'echoes hello world to a file' , function (srcpath, destpath) {Residency
Those grunt log comments can equivalently be replaced with console.log() commands.Residency
R
10

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

      }
    }
);
Residency answered 19/12, 2012 at 20:31 Comment(2)
Note that the done() command is called with the ternary operator, which passes it the error for logging if the asych task had a little problem. See .message property.Residency
UPDATE to above comment: it was done( (error) ? error : ''); technique changed from the ternary operator to simply done(error); Per discussion on #grunt IRC channelResidency

© 2022 - 2024 — McMap. All rights reserved.