Proper way to organize myapp/routes/*

后端 未结 1 678
名媛妹妹
名媛妹妹 2020-12-23 21:10

Using latest stable node.js and express from npm, I\'ve created my first express project.

The default generated app defines routes/index.js, which contains a single

相关标签:
1条回答
  • 2020-12-23 21:35

    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.

    0 讨论(0)
提交回复
热议问题