Loading Node.js modules dynamically based on route

前端 未结 3 1371
情话喂你
情话喂你 2020-12-02 13:47

I\'m doing a project in Node.js using express. Here\'s my directory structure:

root
|-start.js
|-server.js
|-lib/
|    api/
|        user_getDetails.js
|             


        
3条回答
  •  我在风中等你
    2020-12-02 14:10

    app.js

    var c_file = 'html.js';
    
    var controller = require(c_file);
    var method = 'index';
    
    if(typeof controller[method] === 'function')
        controller[method]();
    

    html.js

    module.exports =
    {
        index: function()
        {
            console.log('index method');
        },
        close: function()
        {
            console.log('close method');    
        }
    };
    

    dynamizing this code a little bit you can do magic things :D

提交回复
热议问题