Jishnu Raj
Jishnu Raj

Reputation: 220

Express: How to require a file in node js express and pass a parameter value to it?

This question has a big relation with How to require a file in node.js and pass an argument in the request method, but not to the module? -- Question.

I have a node js Express app. when visitor visits http://localhost/getPosts, the main node js file requires ./routes/posts file and sends a database connection to the required file.

app.use('/getPosts', require('./routes/posts')(myDatabase));

the content of ./routes/posts file is given below:

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

//Do something with myDatabase here

router.get('/', (req, res, next) => {
    res.render('index');
});
module.exports = router;

My website has multiple pages that is, database connection is required on multiple pages. But it is not possible to make mutiple connection to the same database with the same client(Node JS server). that is why I tried adding the connection code in the main page. how do I get the myDatabase variable on the commented area of the code ?

Upvotes: 0

Views: 223

Answers (1)

Eliran Pe'er
Eliran Pe'er

Reputation: 2639

You should export a function that returns the router, like that:

module.exports = dbConnection => {
    var express = require('express');
    var router = express.Router();

    router.get('/', (req, res, next) => {
        res.render('index');
    });

    return router;
};

Upvotes: 1

Related Questions