Ajouve
Ajouve

Reputation: 10089

Global variable express node.js

I am trying to get variables that I can get everywhere in my code I found a solution but that's not very clean

//environment.js    
module.exports.appName = "appName";

and my app.js

var express = require('express')
, routes = require('./routes/main')
, user = require('./routes/user')
, http = require('http')
, path = require('path');

var app = express();

environment = require('./environment');

app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
  app.use(express.errorHandler());
});


app.get('/', routes.home);
app.get('/users', user.list);

http.createServer(app).listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
});

In this way my var works, I can access environment.appName everywhere, but Y would have better solution

Thanks

Upvotes: 5

Views: 14610

Answers (1)

xiaoyi
xiaoyi

Reputation: 6741

There is a global scope in node.js.

In the main file (the one you put behind node in command line,) all variables defined are in global scope.

var x = 100;
// which global.x === 100

And in other files loaded as module, the scope is not global but a local sandbox object, so you need global.x to access the same x in main file.

Seems it looks better than use a require().

Upvotes: 10

Related Questions