Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global Variable in app.js accessible in routes?

How do i set a variable in app.js and have it be available in all the routes, atleast in the index.js file located in routes. using the express framework and node.js

like image 674
Technupe Avatar asked Mar 19 '12 04:03

Technupe


3 Answers

It is actually very easy to do this using the "set" and "get" methods available on an express object.

Example as follows, say you have a variable called config with your configuration related stuff that you want to be available in other places:

In app.js:

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

app.configure(function() {
  ...
  app.set('config', config); 
  ...
}

In routes/index.js

exports.index = function(req, res){
  var config = req.app.get('config');
  // config is now available
  ...
}
like image 83
Mandy Avatar answered Nov 20 '22 11:11

Mandy


A neat way to do this is to use app.locals provided by Express itself. Here is the documentation.

// In app.js:
app.locals.variable_you_need = 42;

// In index.js
exports.route = function(req, res){
    var variable_i_needed = req.app.locals.variable_you_need;
}
like image 37
Ali Avatar answered Nov 20 '22 10:11

Ali


To make a global variable, just declare it without the var keyword. (Generally speaking this isn't best practice, but in some cases it can be useful - just be careful as it will make the variable available everywhere.)

Here's an example from visionmedia/screenshot-app

file app.js:

/**
 * Module dependencies.
 */

var express = require('express')
  , stylus = require('stylus')
  , redis = require('redis')
  , http = require('http');

app = express();

//... require() route files

file routes/main.js

//we can now access 'app' without redeclaring it or passing it in...

/*
 * GET home page.
 */

app.get('/', function(req, res, next){
  res.render('index');
});

//...
like image 69
Jesse Fulton Avatar answered Nov 20 '22 11:11

Jesse Fulton