0

here is some code

// app.js
let foo = 3;
let bar = 35;

in the browser i could do window.foo and i will get my 3, and if i make window.bank = 'lalala' it will be the same as i would wrote

let foo = 3;
let bar = 35;
let bank = 'lalala'

I need the same thing in Node.js, the object which references the global scope of the module. I know about global variable, but it is not that i need, because i want to locally global to current module, not the entire node application

NXTaar
  • 21
  • 1
  • 4
  • http://stackoverflow.com/questions/10987444/how-to-use-global-variable-in-node-js – lastboy Mar 20 '16 at 13:08
  • In node, those are not global variables, but [local module ones](http://stackoverflow.com/q/15406062/1048572). Use an object if you need to access anything by (property) name. – Bergi Mar 20 '16 at 13:09

1 Answers1

1

here is some code

// app.js
let foo = 3;
let bar = 35;

in the browser i could do window.foo and i will get my 3

Not in a browser using a JavaScript engine that correctly implements let you won't. let creates a global variable, but not a property on the global object. This is a new concept in ES2015. (So do const and class.) But if you had used var instead of let, yes, it would show up as a property of the global object (which you can access as window) in a browser.

How to access module global varibales in Node.js

There is no built-in mechanism. NodeJS runs your code within a module scoping function, and so variables you declare at the top level of that code are not globals, and are not automatically added to any accessible object.

If you want them accessible on an object, you'll need to use an object explicitly:

let locals = {  // or even `const locals = {` since you won't change the object, just its properties
    foo: 3,
    bar: 35
};

(In loose mode it would be possible to then use them without an explicit reference to locals, but I recommend always using strict mode, and recommend not using said mechanism (the much-maligned with statement) even if you're in loose mode. with is much-maligned, and disabled in strict mode, for a reason. :-) I mention it only for completeness.)


For true globals, you could use NodeJS's global global, but of course it's generally best to avoid global variables.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875