我正在编写一个自耕农生成器。
复制所有文件后,我需要运行一些 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
}
}
所以我发现唯一可以运行spawn的地方是“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));
但是“end”处理程序没有“dine”回调的参数。
如何做到这一点?
更新:
感谢@SimonBoudrias,我让它工作了。
完整的工作代码如下。
顺便说一句:end
方法在 docs 中描述。
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
}
});
最佳答案
切勿在 end
事件中触发任何操作。该事件由实现者使用,而不是生成者本身。
就您而言:
module.exports = generators.Base({
end: function () {
var done = this.async();
this.spawnCommand('createdb.cmd').on('close', done);
}
});
关于node.js - 自耕农生成器 : how to run async command after all files copied,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28838386/