3

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...

Alvaro
  • 40,778
  • 30
  • 164
  • 336

2 Answers2

4

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

user3366706
  • 1,529
  • 3
  • 31
  • 54
1

You can leave out the var and do just request = require('request'); but this is frowned upon.

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

Jordonias
  • 5,778
  • 2
  • 21
  • 32