Yeoman生成器:如何在复制所有文件后运行async命令

时间:2015-03-03 17:43:30

标签: node.js yeoman yeoman-generator

我正在写一个自耕农发电机。 我需要在复制所有文件后运行一些shell脚本。 生成器被称为子生成器,所以它应该等到脚本完成 该脚本是通过spawn运行的一些命令文件:

that.spawnCommand('createdb.cmd');

由于脚本依赖于生成器创建的文件,因此无法在生成器的方法中运行,因为所有复制/模板操作都是异步的并且尚未执行:

MyGenerator.prototype.serverApp = function serverApp() {
  if (this.useLocalDb) {
    this.copy('App_Data/createdb.cmd', 'App_Data/createdb.cmd');
    // here I cannot run spawn with createdb.cmd as it doesn't exist
  }
}

所以我找到的唯一可以运行产卵的地方就是' end'事件处理程序:

var MyGenerator = module.exports = function MyGenerator (args, options, config) {
  this.on('end', function () {
    if (that.useLocalDb) {
      that.spawnCommand('createdb.cmd')
    }
  }
}

脚本成功运行,但生成器早于子进程完成。我需要告诉Yeoman等我的孩子过程。 像这样:

this.on('end', function (done) {
  this.spawnCommand('createdb.cmd')
    .on('close', function () {
      done();
    });
}.bind(this));

但是'结束'处理程序没有与' dine'打回来。

怎么做?

更新
感谢@SimonBoudrias,我得到了它的工作 完整的工作代码如下 BTW:docs

中描述了end方法
var MyGenerator = module.exports = yeoman.generators.Base.extend({
    constructor: function (args, options, config) {
        yeoman.generators.Base.apply(this, arguments);
        this.appName = this.options.appName;
    },

    prompting : function () {   
        // asking user
    },

    writing : function () { 
        // copying files
    },

    end: function () {
        var that = this;
        if (this.useLocalDb) {
            var done = this.async();
            process.chdir('App_Data');

            this.spawnCommand('createdb.cmd').on('close', function () {
                that._sayGoodbay();
                done();
            });

            process.chdir('..');
        } else {
            this._sayGoodbay();
        }
    },

    _sayGoodbay: funciton () {
        // final words to user
    }
});

1 个答案:

答案 0 :(得分:2)

永远不要在end事件中触发任何操作。此事件将由实现者使用,而不是生成器本身。

在你的情况下:

module.exports = generators.Base({
    end: function () {
        var done = this.async();
        this.spawnCommand('createdb.cmd').on('close', done);
    }
});
相关问题