在我的NodeJS express应用程序中,我有app.js,它有一些常见的路由。然后在wf.js文件中,我想定义更多的路由。

如何让app.js识别在wf.js文件中定义的其他路由处理程序?

一个简单的要求似乎不起作用。


当前回答

所有这些答案的一个调整:

var routes = fs.readdirSync('routes')
      .filter(function(v){
         return (/.js$/).test(v);
      });

只需使用正则表达式通过测试数组中的每个文件进行筛选。它不是递归的,但它会过滤掉不以.js结尾的文件夹

其他回答

在前面答案的基础上,这个版本的routes/index.js将忽略任何以.js(和它本身)结尾的文件。

var fs = require('fs');

module.exports = function(app) {
    fs.readdirSync(__dirname).forEach(function(file) {
        if (file === "index.js" || file.substr(file.lastIndexOf('.') + 1) !== 'js')
            return;
        var name = file.substr(0, file.indexOf('.'));
        require('./' + name)(app);
    });
}

如果你想要一个单独的.js文件来更好地组织你的路由,只需在app.js文件中创建一个变量,指向它在文件系统中的位置:

var wf = require(./routes/wf);

然后,

app.get('/wf', wf.foo );

其中.foo是wf.js文件中声明的某个函数。如

// wf.js file 
exports.foo = function(req,res){

          console.log(` request object is ${req}, response object is ${res} `);

}

基于@ShadowCloud的例子,我能够在子目录中动态地包含所有路由。

路线/ index.js

var fs = require('fs');

module.exports = function(app){
    fs.readdirSync(__dirname).forEach(function(file) {
        if (file == "index.js") return;
        var name = file.substr(0, file.indexOf('.'));
        require('./' + name)(app);
    });
}

然后将路由文件放在routes目录中,如下所示:

路线/ test1.js

module.exports = function(app){

    app.get('/test1/', function(req, res){
        //...
    });

    //other routes..
}

根据需要重复多次,最后在app.js中放置

require('./routes')(app);

在快车4号。X,你可以得到一个路由器对象的实例,并导入另一个包含更多路由的文件。您甚至可以递归地执行此操作,以便您的路由导入其他路由,从而允许您创建易于维护的URL路径。

例如,如果我的/tests端点已经有一个单独的路由文件,并且想为/tests/automated添加一组新的路由,我可能想将这些/automated路由分解到另一个文件中,以保持/test文件小且易于管理。它还可以让你在逻辑上把路由按URL路径组合在一起,这非常方便。

./app.js的内容:

var express = require('express'),
    app = express();

var testRoutes = require('./routes/tests');

// Import my test routes into the path '/test'
app.use('/tests', testRoutes);

./routes/tests.js的内容:

var express = require('express'),
    router = express.Router();

var automatedRoutes = require('./testRoutes/automated');

router
  // Add a binding to handle '/tests'
  .get('/', function(){
    // render the /tests view
  })

  // Import my automated routes into the path '/tests/automated'
  // This works because we're already within the '/tests' route 
  // so we're simply appending more routes to the '/tests' endpoint
  .use('/automated', automatedRoutes);
 
module.exports = router;

./routes/testRoutes/ automatic .js文件的内容:

var express = require('express'),
    router = express.Router();

router
   // Add a binding for '/tests/automated/'
  .get('/', function(){
    // render the /tests/automated view
  })

module.exports = router;

index.js

const express = require("express");
const app = express();
const http = require('http');
const server = http.createServer(app).listen(3000);
const router = (global.router = (express.Router()));
app.use('/books', require('./routes/books'))
app.use('/users', require('./routes/users'))
app.use(router);

路线/ users.js

const router = global.router
router.get('/', (req, res) => {
    res.jsonp({name: 'John Smith'})
}

module.exports = router

路线/ books.js

const router = global.router
router.get('/', (req, res) => {
    res.jsonp({name: 'Dreams from My Father by Barack Obama'})
}

module.exports = router

如果您的服务器在本地运行(http://localhost:3000),那么

// Users
curl --request GET 'localhost:3000/users' => {name: 'John Smith'}

// Books
curl --request GET 'localhost:3000/books' => {name: 'Dreams from My Father by Barack Obama'}