0

Currently I am doing full stack javascript development using node,express. My question is how to make a variable at app.js/server and can be access by all its controllers without any further declaration. (Something like static variable in java, you don't need to do anything, just use that variable like class.variable)

If it is impossible, what is a way to get around this?

jiancheng wu
  • 605
  • 2
  • 7
  • 9
  • Just import it in every file where you define controllers. – ideaboxer Sep 02 '17 at 20:44
  • 1
    If all controllers have access to the `app` object, you can use [`app.get()`](http://expressjs.com/en/4x/api.html#app.get) and [`app.set()`](http://expressjs.com/en/4x/api.html#app.set) or you can just directly add a property to the `app` object. If you show us an example code for your controller, we could likely offer more ideas. – jfriend00 Sep 02 '17 at 20:53
  • Creating a config file and using the variables by importing it everywhere is the standard practice if you are talking about config variables. – Kshitij Mittal Sep 02 '17 at 21:19

3 Answers3

0

I'm not familar with express but I think the common way of declaring static members in JS might help.

function Class1(dyn_member){
    this.dyn_member=dyn_member;
}
Object.defineProperty(Class1.prototype,'static_member',{
    get:function(){return Class1.static_member},
    set:function(value){Class1.static_member=value;}
});

a=new Class1('dyn1');
b=new Class1('dyn2');
console.log(a.static_member);
a.static_member='new static';
console.log(b.static_member);
Ben
  • 410
  • 3
  • 11
0

You define such variables in config file. Also good point will be to split config file into different deployment environments.

Nice package to discover would be config.

Lazyexpert
  • 3,106
  • 1
  • 19
  • 33
-1

You add this variable to global scope and access it from any javascript file.

//set variable
global.myVar = 'Something';

//get variable
console.log(global.myVar);
abskmj
  • 760
  • 3
  • 6
  • In general, you want to avoid using global variables in node.js server development as it messes with modularity and code reuse and creates opportunities for naming conflicts. node development encourages that things are shared with import and export or via module constructors, not via globals. – jfriend00 Sep 02 '17 at 20:54
  • global should be used wisely because it can very easily create a mess. see comments in this answer https://stackoverflow.com/a/10987543/3439731 – Raghav Garg Sep 02 '17 at 20:54