本文旨在手写mini-cac.js。
精简逻辑,实现cac.js基础api,帮助读者理解cac.js源码流程。
1.测试例子
2.mini-cac.js实现
(1)事件监听。
即测试例子中cli.on,这里使用node的events模块实现,第(3)步中CAC继承events.EventEmitter,CAC便有了事件监听、触发、移除等方法。
var events = require('events');
(2)command类
class Command{
constructor(rawName,description){
this.rawName = rawName;
this.description = description;
this.commandAction = null;
}
action(callback) {
this.commandAction = callback;
return this;
}
}
(3)CAC类
class CAC extends events.EventEmitter{
constructor(rawName,description){
super();
this.rawName = rawName;
this.description = description;
this.commands = null;
}
command(rawName,description){
const command = new Command(rawName,description || '');
this.commands = command;
return command;
}
parse(){
//处理数据,整理数据格式,略
//触发事件
this.emit(`command:${this.commands.rawName}`, this.commands);
//执行命令
this.runMatchedCommand();
}
runMatchedCommand(){
var params = process.argv;//process.argv 用户输入的参数
this.commands.commandAction.call(this,params[3] ? params[3] : { '--': [] }); //参数写死,只作例子
}
}
(4)导出cac
const cac = ()=>{
return new CAC();
}
module.exports = {
cac,
}
(5)测试