79 lines
1.6 KiB
JavaScript
79 lines
1.6 KiB
JavaScript
const Koa = require("koa")
|
|
const glob = require("glob")
|
|
const path = require('path')
|
|
const xe = require("xe-utils")
|
|
|
|
/**
|
|
* bamboo 核心
|
|
* @param {string} extend_directory 扩展库目录
|
|
*/
|
|
module.exports = class Bamboo extends Koa {
|
|
/*初始化业务目录*/
|
|
constructor(extend_directory, root) {
|
|
super();
|
|
this.xe = xe
|
|
this.root = this.isPath() || root;
|
|
this.extend_directory = extend_directory || `extend/*/index.js`
|
|
this.willReadyList = []
|
|
console.log(`当前根目录${this.root}`);
|
|
console.log(`当前插件目录${this.extend_directory}`);
|
|
this.loadEvent()
|
|
}
|
|
|
|
/*加载扩展库目录*/
|
|
async loadEvent() {
|
|
const list = await this.load(this.extend_directory)
|
|
for (let listElement of list) {
|
|
await listElement.res(this)
|
|
}
|
|
this.willReadyList.push(() => {
|
|
this.startServer()
|
|
})
|
|
await this.willReady()
|
|
}
|
|
|
|
|
|
/*扩展已经加载完成触发*/
|
|
async willReady() {
|
|
for (let WRL of this.willReadyList) {
|
|
await WRL()
|
|
}
|
|
}
|
|
|
|
/*当前根目录*/
|
|
isPath(args) {
|
|
return path.resolve('./' + (args || ""))
|
|
}
|
|
|
|
/*加载文件*/
|
|
load(directory, root) {
|
|
const path_root = root || this.root
|
|
return new Promise((resolve, reject) => {
|
|
const options = {
|
|
root: path_root
|
|
}
|
|
glob(directory, options, function (er, files) {
|
|
if (er) {
|
|
reject(er)
|
|
}
|
|
// console.log("获取到的文件:", files);
|
|
files = files.map(item => {
|
|
const parse = path.parse(item);
|
|
return {
|
|
parse,
|
|
res: require(path.resolve(path_root + "/" + item))
|
|
}
|
|
})
|
|
resolve(files)
|
|
})
|
|
})
|
|
}
|
|
|
|
|
|
/*启动服务*/
|
|
startServer(prod) {
|
|
this.listen(prod || 3000)
|
|
console.log('启动服务:3000');
|
|
}
|
|
}
|