Search code examples
node.jsexpressexpress-4

Include a module for all routes at express.js 4


I'm using Express 4.2.0

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

Right now this won't work:

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;

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

ReferenceError: request is not defined at Object.module.exports [as handle] (C:\inetpub\wwwroot\node7\routes\users. js:12:5)

Having to include modules in every route which wants to use them doesn't sound like a proper solution...


Solution

  • Yes, there are two ways of creating global variables in Node.js, one using the global object, and the other using module.exports

    Here is how,

    Method 1. Declare variable without var keyword. Just like importModName = require('modxyz') and it will be stored in global object so you can use it anywhere like global.importModName

    Method 2. Using exports option. var importModName = require('modxyz'); module.exports = importModName ; and you can use it in other modules.

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