Lukas
Lukas

Reputation: 437

Passing arguments to require, when loading a router module with express router

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

var route = new Route();
route.data = data
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);

Upvotes: 0

Views: 299

Answers (1)

uranshishko
uranshishko

Reputation: 312

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)

Upvotes: 1

Related Questions