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 ...
source to share
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
source to share