Express: How to pass app-instance to routes from a different file?

后端 未结 8 1047
误落风尘
误落风尘 2020-11-29 16:34

I want to split up my routes into different files, where one file contains all routes and the other one the corresponding actions. I currently have a solution to achieve thi

8条回答
  •  -上瘾入骨i
    2020-11-29 16:49

    Let's say that you have a folder named "contollers".

    In your app.js you can put this code:

    console.log("Loading controllers....");
    var controllers = {};
    
    var controllers_path = process.cwd() + '/controllers'
    
    fs.readdirSync(controllers_path).forEach(function (file) {
        if (file.indexOf('.js') != -1) {
            controllers[file.split('.')[0]] = require(controllers_path + '/' + file)
        }
    });
    
    console.log("Controllers loaded..............[ok]");
    

    ... and ...

    router.get('/ping', controllers.ping.pinging);
    

    in your controllers forlder you will have the file "ping.js" with this code:

    exports.pinging = function(req, res, next){
        console.log("ping ...");
    }
    

    And this is it....

提交回复
热议问题