定义 ./modules/index.js
const fs = require("fs");
const colors = require("colors");
module.exports = {
controller: null,
path: '',
init: function(path, controller) {
if (!controller) {
console.error("参数controller未设置");
return false;
}
this.controller = controller;
this.path = path ? path : this.path;
this.listDir(this.path);
},
listDir: function(dir) {
var fileList = fs.readdirSync(dir, 'utf-8');
for (var i = 0; i < fileList.length; i++) {
if (fileList[i] == 'index.js') continue;
var stat = fs.lstatSync(dir + fileList[i]);
if (stat.isDirectory()) {
this.listDir(dir + fileList[i] + '/');
} else {
this.loadRoute(dir + fileList[i]);
}
}
},
loadRoute: function(routeFile) {
let filename = routeFile.substring(routeFile.lastIndexOf('/') + 1);
let current_filename = './' + filename.substring(0, filename.lastIndexOf('.'));
require(current_filename)(this.controller);
console.log(`module [${filename.substring(0, filename.lastIndexOf('.'))}] load success.`.green);
},
};
调用
modules.init('./modules/', controller);
评论 (0)