Include module for all routes in express.js 4

I am using Express 4.2.0

Is it possible to include a module only once in app.js and use it in any specific route?

It won't work now:

app.js

//..
var request = require('request');

var routes = require('./routes/index');
var users = require('./routes/users');

app.use('/', routes);
app.use('/users', users);
//...

      


routes / user.js

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

router.get('/add', function(req, res) {
    var session = req.session;
    request('http://localhost:8181/Test?val1=getDepartments', function (error, response, body) {
       //...
    });

    res.render('users/add');
});

module.exports = router;

      

He will say that "request" is not defined in routes/user.js

ReferenceError: Request not defined in Object.module.exports [as descriptor] (C: \ inetpub \ wwwroot \ node7 \ routes \ users. JS: 12: 5)

Having modules in every route that wants to use them doesn't sound like the right decision ...

+3


source to share


2 answers


Yes, there are two ways to create global variables in Node.js, one with global object

and the other withmodule.exports

That's how,

Method 1. Declare a variable without the var keyword. Just like importModName = require('modxyz')

, and it will be stored in a global object, so you can use it anywhere, likeglobal.importModName



Method 2. Using the export option. var importModName = require('modxyz'); module.exports = importModName ;

and you can use it in other modules.

Look at somemore explanation http://www.hacksparrow.com/global-variables-in-node-js.html

+4


source


You can only leave var

and do request = require('request');

, but it is incredulous.



Node.js caches modules. The standard approach is to use modules where needed.

+1


source







All Articles