nodejs动态加载文件夹内模块

nodejs动态加载文件夹内模块

2018-05-03 / 0 评论 / 121 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2021年10月27日,已超过1121天没有更新,若内容或图片失效,请留言反馈。

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

评论 (0)

取消