Proper way to organize myapp/routes/*

戏子无情 提交于 2019-11-29 22:17:47

I prefer dynamically loading routes instead of having to manually add another require each time you add a new route file. Here is what I am currently using.

var fs = require('fs');

module.exports = function(app) {
    console.log('Loading routes from: ' + app.settings.routePath);
    fs.readdirSync(app.settings.routePath).forEach(function(file) {
        var route = app.settings.routePath + file.substr(0, file.indexOf('.'));
        console.log('Adding route:' + route);
        require(route)(app);
    });
}

I call this when the application loads, which then requires all files in the routePath. Each route is setup like the following:

module.exports = function(app) {
    app.get('/', function(req, res) {
        res.render('index', {
            title: 'Express'
        });
    });
}

To add more routes, all you have to do now is add a new file to the routePath directory.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!