Home > Back-end >  How to read all routes dynamically in node.js
How to read all routes dynamically in node.js

Time:12-24

I am trying to read all routes in my app.js file from './routes' folder,but gettingerror:"TypeError: Cannot read property 'forEach' of undefined"

           import express from "express";
           import fs from "fs";
           const app = express();
           fs.readdir('./routes', (err, fs) => {
           fs.forEach(file => {
           app.use('/', require('./routes/'   file))
                             });
                   })
          export default app

CodePudding user response:

This worked for me:

sync

fs.readdirSync('/some/path/routes').forEach(function(file) {
  app.use('/', require(`/some/path/routes/`   file));
});

async

fs.readdir('/some/path/routes', function(err, files){
  files.forEach(function(file){
    app.use('/', require(`/some/path/routes/`   file));
  });
});

CodePudding user response:

You can do using fs.readdirSync because the server is not yet started.

fs.readdir(`${__dirname}/routes`, (err, files) => {
  if (err)
    console.log(err);
  else {
    files.forEach(file => {
      app.use('/', require(`${__dirname}/routes`   file));
    })
  }
})

You can use fspromise and import to handle using promise.

  • Related