express递归读取routes

根目录下创建一个lib文件夹并创建一个boot.js文件,文件内容如下:

var fs = require('fs');
var path = require('path');

module.exports = function (app) {
    var dir = path.join(__dirname, '..', 'routes');
    module.exports.SetRoutes(app, dir);
}
module.exports.SetRoutes = function (app, dir) {
    fs.readdirSync(dir).forEach(function (name) {
        var filepath = path.join(dir, name);
        if (fs.statSync(filepath).isFile() && filepath.indexOf('.js') != -1) {

            var filedirname = filepath.replace('.js', '');
            var uri = filedirname.replace(path.join(__dirname, '..', 'routes'), '');
            var routeObj = require(filedirname);
            try {
                app.use(uri, routeObj)
            } catch (e) {
                console.error(e, filepath)
            }
        } else {
            module.exports.SetRoutes(app, filepath);
        }
    })
}

app.js文件中添加下面一行代码:

// var index = require('./routes/index');
// var users = require('./routes/users');
// app.use('/', index);
// app.use('/users', users);

require('./lib/boot')(app);


你可能感兴趣的:(express递归读取routes)