ryanzec ryanzec - 2 months ago 14
Javascript Question

Custom NodeJS Grunt Command

I have a custom grunt task that looks like this:

grunt.registerTask('list', 'test', function()
{
var child;
child = exec('touch skhjdfgkshjgdf',
function (error, stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
});
});


This works however when I try to run the pwd command, I don't get any output. The end goal of this is to be able to compile sass files with grunt and I figure the best way of doing that is by running the the command line command to compile sass through grunt however I want to get some sort of output to the screen that is worked properly. Is there any reason this code would not print the results of running unix commands through grunt/nodejs?

Answer

exec() is async so you need to tell grunt that and execute the callback when it's done:

grunt.registerTask('list', 'test', function()
{
    // Tell grunt the task is async
    var cb = this.async();

    var child = exec('touch skhjdfgkshjgdf', function (error, stdout, stderr) {
        if (error !== null) {
          console.log('exec error: ' + error);
        }

        console.log('stdout: ' + stdout);
        console.log('stderr: ' + stderr);

        // Execute the callback when the async task is done
        cb();
    });
});

From grunt docs: Why doesn't my asynchronous task complete?

Comments