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
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
}
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With