0

Is there way to define global variable which will be available inside some module. So, if we have module test, and inside test we have files index.js, test1.js, test2.js, can we define variable inside index.js to be available in test1.js and test2.js, but not outside this module?

Exact situation:

So, I am using some npm module and I don't want to require that module every time, but only within one directory, not whole node application, because that can cause problems to me.

user232343
  • 2,008
  • 5
  • 22
  • 34
  • just don't put "var " in front of the variable declaration... – dandavis Mar 14 '14 at 20:30
  • Show a code structure example of what you're trying to do as it is not very clear what you are asking for. If you define a function scope, then any variables defined in that scope will be available to ALL code within that scope, but not available to code outside that scope. – jfriend00 Mar 14 '14 at 20:34
  • that is throwing error....variable is not defined (in strict mode) – user232343 Mar 14 '14 at 20:34
  • Also, I think you should remove the word "global" from your question title because what you're asking for is NOT a global variable. – jfriend00 Mar 14 '14 at 20:37
  • I edited question...is now clear? – user232343 Mar 14 '14 at 20:37
  • BTW: Using multiple `require`s is without overhead since it caches modules. – Pritam Baral Mar 14 '14 at 20:58

2 Answers2

1

test1.js:

exports = test1Module = { func1: function(...){...}, func2: function(...){...}, func3: function(...){ console.log(test1Module.secretVariable); } }

index.js:
var secretVariable = "secretValue"; var test1 = require('test1'); test1.secretVariable = secretVariable;

And similarly with test2, but NOT test3..

Pritam Baral
  • 475
  • 2
  • 7
0

What you are looking for is namespaces.

Take a look at the following How do I declare a namespace in JavaScript?

var yourNamespace = {

    foo: function() {
    },

    bar: function() {
    }
};

...

yourNamespace.foo();
Community
  • 1
  • 1
Marko
  • 2,734
  • 24
  • 24
  • 2
    Are you saying that he should create a namespace and attach it to `global`? That wouldn't limit it to just that module like he wants. Anything attached to `global` would be available to any module in the running process. – CatDadCode Mar 14 '14 at 20:57