根据路由动态加载Node.js模块

23 javascript api prototype v8 node.js

我正在使用express在Node.js中做一个项目.这是我的目录结构:

root
|-start.js
|-server.js
|-lib/
|    api/
|        user_getDetails.js
|        user_register.js
Run Code Online (Sandbox Code Playgroud)

lib/api/目录有许多与API相关的JS文件.我需要做的是制作一种挂钩系统,无论何时从快速HTTP服务器请求其中一个API函数,它都会执行相应API处理程序中指定的任何操作.这可能令人困惑,但希望你能得到这个想法.

  1. Larry通过POST发送请求以获取用户详细信息.
  2. 服务器查找lib/api与该请求关联的功能.
  3. 服务器执行操作并将数据发送回Larry.

希望你能帮助我.我当时认为可以使用原型来完成,但不确定.

谢谢!

fre*_*ish 29

如果您知道脚本的位置,例如DIR,您有一个初始目录,那么您可以使用fs,例如:

server.js

var fs = require('fs');
var path_module = require('path');
var module_holder = {};

function LoadModules(path) {
    fs.lstat(path, function(err, stat) {
        if (stat.isDirectory()) {
            // we have a directory: do a tree walk
            fs.readdir(path, function(err, files) {
                var f, l = files.length;
                for (var i = 0; i < l; i++) {
                    f = path_module.join(path, files[i]);
                    LoadModules(f);
                }
            });
        } else {
            // we have a file: load it
            require(path)(module_holder);
        }
    });
}
var DIR = path_module.join(__dirname, 'lib', 'api');
LoadModules(DIR);

exports.module_holder = module_holder;
// the usual server stuff goes here
Run Code Online (Sandbox Code Playgroud)

现在您的脚本需要遵循以下结构(因为该require(path)(module_holder)行),例如:

user_getDetails.js

function handler(req, res) {
    console.log('Entered my cool script!');
}

module.exports = function(module_holder) {
    // the key in this dictionary can be whatever you want
    // just make sure it won't override other modules
    module_holder['user_getDetails'] = handler;
};
Run Code Online (Sandbox Code Playgroud)

现在,在处理请求时,您执行以下操作:

// request is supposed to fire user_getDetails script
module_holder['user_getDetails'](req, res);
Run Code Online (Sandbox Code Playgroud)

这应该将所有模块加载到module_holder变量.我没有测试它,但它应该工作(除了错误处理!!!).您可能想要更改此功能(例如,创建module_holder一个树,而不是一个级别的字典),但我认为您将掌握这个想法.

这个函数应该在每个服务器启动时加载一次(如果你需要更频繁地启动它,那么你可能正在处理动态服务器端脚本,这是一个baaaaaad想法,imho).您现在唯一需要的是导出module_holder对象,以便每个视图处理程序都可以使用它.

  • 如果您在启动时调用该函数一次,则没有理由使用异步版本;只需使用`fs.lstatSync` 和`fs.readdirSync`。这也会阻止您吞下错误,因为将抛出异常,而不是将错误传递给回调然后被忽略。 (2认同)

ZiT*_*TAL 6

应用程序.js

var c_file = 'html.js';

var controller = require(c_file);
var method = 'index';

if(typeof controller[method] === 'function')
    controller[method]();
Run Code Online (Sandbox Code Playgroud)

html.js

module.exports =
{
    index: function()
    {
        console.log('index method');
    },
    close: function()
    {
        console.log('close method');    
    }
};
Run Code Online (Sandbox Code Playgroud)

稍微动态化这段代码,你可以做一些神奇的事情:D