Loading Node.js modules dynamically based on route

前端 未结 3 1345
情话喂你
情话喂你 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:17

    Here is an example of a REST API web service that dynamically loads the handler js file based on the url sent to the server:

    server.js

    var http = require("http");
    var url = require("url");
    
    function start(port, route) {
       function onRequest(request, response) {
           var pathname = url.parse(request.url).pathname;
           console.log("Server:OnRequest() Request for " + pathname + " received.");
           route(pathname, request, response);
       }
    
       http.createServer(onRequest).listen(port);
       console.log("Server:Start() Server has started.");
    }
    
    exports.start = start;
    

    router.js

    function route(pathname, req, res) {
        console.log("router:route() About to route a request for " + pathname);
    
        try {
            //dynamically load the js file base on the url path
            var handler = require("." + pathname);
    
            console.log("router:route() selected handler: " + handler);
    
            //make sure we got a correct instantiation of the module
            if (typeof handler["post"] === 'function') {
                //route to the right method in the module based on the HTTP action
                if(req.method.toLowerCase() == 'get') {
                    handler["get"](req, res);
                } else if (req.method.toLowerCase() == 'post') {
                    handler["post"](req, res);
                } else if (req.method.toLowerCase() == 'put') {
                    handler["put"](req, res);
                } else if (req.method.toLowerCase() == 'delete') {
                    handler["delete"](req, res);
                }
    
                console.log("router:route() routed successfully");
                return;
            } 
        } catch(err) {
            console.log("router:route() exception instantiating handler: " + err);
        }
    
        console.log("router:route() No request handler found for " + pathname);
        res.writeHead(404, {"Content-Type": "text/plain"});
        res.write("404 Not found");
        res.end();
    
    }
    
    exports.route = route;
    

    index.js

    var server = require("./server");
    var router = require("./router");
    
    server.start(8080, router.route);
    

    handlers in my case are in a subfolder /TrainerCentral, so the mapping works like this:

    localhost:8080/TrainerCentral/Recipe will map to js file /TrainerCentral/Recipe.js localhost:8080/TrainerCentral/Workout will map to js file /TrainerCentral/Workout.js

    here is a example handler that can handle each of the 4 main HTTP actions for retrieving, inserting, updating, and deleting data.

    /TrainerCentral/Workout.js

    function respond(res, code, text) {
        res.writeHead(code, { "Content-Type": "text/plain" });
        res.write(text);
        res.end();
    }
    
    module.exports = {
       get: function(req, res) {
           console.log("Workout:get() starting");
    
           respond(res, 200, "{ 'id': '123945', 'name': 'Upright Rows', 'weight':'125lbs' }");
       },
       post: function(request, res) {
           console.log("Workout:post() starting");
    
           respond(res, 200, "inserted ok");
       },
       put: function(request, res) {
           console.log("Workout:put() starting");
    
           respond(res, 200, "updated ok");
       },
       delete: function(request, res) {
           console.log("Workout:delete() starting");
    
           respond(res, 200, "deleted ok");
       }
    };
    

    start the server from command line with "node index.js"

    Have fun!

提交回复
热议问题