nodejs动态加载文件夹内模块

dhso
2018/05/04 02:00
统计中

定义 ./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);

本文为 dhso 原创

发布在 http://blog.minws.com/nodejsdong-tai-jia-zai-wen-jian-jia-nei-mo-kuai/

如有转载,请标明来源!

作者信息
姓名:dhso
热评文章
最新评论
文章概览