0

This question is very related to this.

In my module I use following:

const express       = require('express'),
      router        = express.Router();
...
module.exports = router;

And I need access to objects in the app.js file. Something like const routes = require(./routes/route.js)(data).

What I tried

  • module.exports = router(data) But than reqis undefined in the router object.

  • Made an instance of routein app.js after requiring it. But this results in the same error message. (Like this:

var route = new Route();
route.data = data
  • Pretty much the same like in the article I mentioned, but I'm not sure what I have to do with the router object. This does not work:
module.exports = router(data){
// all routes
};

Additional information

I normally use routes like this in app.js

const route = require('route.js');
app.use(route);
Lukas
  • 397
  • 6
  • 21
  • You need to do `module.exports = function (data) {/* code, not routes */}` or `module.exports = (data) => {/*again, NOT routes */}` – slebetman Sep 30 '20 at 10:46

1 Answers1

1

I am not sure if i understood your question, but if you want to pass data to a module that you require you could do something like this:

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

module.exports = function(data) {
   // do stuff with data
   router.get('/', (req, res) => res.send(data))

   return router;
}

// and then in app.js

const router = require('router.js')(/* pass data to router*/);

app.use(router)

uranshishko
  • 312
  • 1
  • 7