/** * 動態遍歷目錄加載路由工具 * author: bling興哥 */ var fs = require("fs"); // 動態路由 var loadRoute = { path : './routes/', app : null, // 遍歷目錄 listDir : function(dir){ var fileList = fs.readdirSync(dir,'utf-8'); for(var i=0;i<fileList.length;i++) { var stat = fs.lstatSync(dir + fileList[i]); // 是目錄,須要繼續 if (stat.isDirectory()) { this.listDir(dir + fileList[i] + '/'); } else { this.loadRoute(dir + fileList[i]); } } }, // 加載路由 loadRoute : function(routeFile){ console.log(routeFile); var route = require(routeFile.substring(0,routeFile.lastIndexOf('.'))); // 在路由文件中定義了一個basePath變量,設置路由路徑前綴 if(route.basePath){ this.app.use(route.basePath,route); }else{ this.app.use(route); } }, // 初始化入口 init : function(app,path){ if(!app){ console.error("系統主參數App未設置"); return false; } this.app = app; this.path = path?path:this.path; this.listDir(this.path); } }; module.exports = loadRoute;