Search code examples
javascriptnode.jsprocessgruntjsspawn

"Close" callback for spawn() function doesn't work in a grunt plugin


I'm creating a grunt plugin what makes an extensive use of the grunt.util.spawnfunction (http://gruntjs.com/api/grunt.util#grunt.util.spawn). The basic skeleton for my plugin is as follows:

'use strict';

module.exports = function (grunt) {

    var spawn = require("child_process").spawn;

    var createCommit = function (text) {
        var commit = grunt.util.spawn({
                    cmd: "git",
                    args: ["commit","-a","-m", text]
        }, function() {
                    console.log("FINISH! FINISH! FINISH!");
        });
    };

    grunt.registerMultiTask("myplugin", "Plugin to commit awesome things", function () {
        createCommit("0.2.0");
    });
};

Nevertheless, when I'm trying to execute this grunk task, the console.log("FINISH! FINISH! FINISH!"); is never executed by mi callback...Someone could help me with this?


Solution

  • Finally I found a solution in this question (Wait async grunt task to finish). The key to solve this is the use of the function this.async inside of the registration. A possible solution could be:

    'use strict';
    
    module.exports = function (grunt) {
    
        var spawn = require("child_process").spawn,
            donePromise;
    
        var createCommit = function (text) {
            var i = 0;
        var commit = grunt.util.spawn({
                cmd: "git",
                args: ["commit","-a","-m", text]
            }, function() {
                callback();
                donePromise();
            });
        };
    
    
       grunt.registerMultiTask("myplugin", "Plugin to commit awesome things", function () {
            donePromise = this.async();
            createCommit("0.3.0");
        });
    };