Ben Diamant
Ben Diamant

Reputation: 6206

ExpressJS: app.get()/app.set() data lifetime

In express.js we can use app.set/get to obtain variables across a request, print them in a jade view and access them in an advanced stage middleware.

But - I can't find in express's documentation what is the lifetime of these variables.

For example if I use:

app.set('my-var', 'here is my var');

And trying to pull it in the same middleware chain:

console.log(app.get('my-var')); // would work

But on a new request middleware chain I get undefined

Can I get a clearance?

Upvotes: 1

Views: 248

Answers (1)

Krzysztof Safjanowski
Krzysztof Safjanowski

Reputation: 7438

As long as no one will not overwrite it, source from express/lib/application.js

app.init() - bootsrapp ExpressJS

this.settings = {};

default configuration - assing settings to locals

this.locals.settings = this.settings;

app.set() - method definition

app.set = function(setting, val){   
  // set value
  this.settings[setting] = val;

app.render() - it is time to render view

app.render = function(name, options, fn){
  var opts = {};
  var view;

  // merge app.locals
  merge(opts, this.locals);

  // merge options._locals
  if (options._locals) {
    merge(opts, options._locals);
  }

  // merge options
  merge(opts, options);

  // render
  try {
    view.render(opts, fn);
  } catch (err) {
    fn(err);
  }
}

there is no magic in ExpressJS - settings and local.settings are merged before render. The are no methods like - clear settings, clear locals. Whatever is set it will be avaible.

Upvotes: 1

Related Questions