Loading multiple express endpoint files to main app

95 Views Asked by At

I'm trying to require/run all the files in a folder but having issues:

Inside Endpoints: index.js;

const { Router } = require("express");
const router = Router();

router.get("/", async (req, res) => {
  res.render("./../../views/home.ejs");
});

module.exports = router;

Inside Core-routers (routers) core.js;

const { readdirSync } = require("fs");
const findEndpoints = readdirSync(__dirname+"/../endpoints");
const endpoints = findEndpoints.filter((c) => c.split(".").pop() === "js");
class Routers {
  constructor(app) {
    this.app = app;
  }
  load() {
    for (let i = 0; i < endpoints.length; i++) {
      if (!endpoints.length) throw Error("No Endpoints Found.");
      this.app.use(require(`${__dirname}/../endpoints/${endpoints[i]}`)("/"));
    }
}
module.exports = Routers;

can someone explain how I can get it load all the endpoints and make them usuable

1

There are 1 best solutions below

3
On

One possible solution however doesnt prevent the 404 or otherwise known as the "*" pages automatically loads and prevents any other page being loaded.

const { readdirSync } = require("fs");
const findEndpoints = readdirSync(`${__dirname}/../endpoints`);
const endpoints = findEndpoints.filter((c) => c.split(".").pop() === "js");

class Routers {
  constructor(app) {
    this.app = app;
  }
  loadEndpoints() {
    for (let i = 0; i < endpoints.length; i++) {
      if (!endpoints.length) throw Error("No Endpoints Found.");
      console.log(endpoints[i]);
      this.app.use("",require(`${__dirname}/../endpoints/${endpoints[i]}`);
    }
  }
}
module.exports = Routers;

If anyone has a solution to prevent above mentioned issue, feel free to contribute.