0

I would like to understand best practice for accessing variables that are defined in an external module that would then be required in several other files.

Say we have the two following files, I would like to access the value of the h variable in consume.js

//central.js
module.exports = {
  common: function() {
      var h = "hello";
      var b = "enabled"
   }
};

and

//consume.js

var g = require('./central');
//get the value of variable h from central.js

Taking this a step further, if I have the following consume.js, fetch.js and get.js files that all imported central.js, and required a common set of variables from central.js, how does one go about defining these common variables inside central.js so that the dependent files can consume them?

Thanks!

2
  • You can't as shown. var h is private to the common function while it is executing. There is no way to reach inside that function from the outside (even from within the same module) to get to h. In fact, when common() is not executing, there is not even an instance of h. Now, you could make common() return h and then call g.common() from anywhere to get the return value of the function. Commented Sep 23, 2017 at 17:30
  • The general answer to how you share from one module to another is that you export functions or objects or properties and then other modules require() in that module and that gives them access to what the module has exported. This is pretty basic module logic in node.js so I'd suggest you read how exporting works from node.js modules and then ask a more specific question. Commented Sep 23, 2017 at 17:32

1 Answer 1

1

Export:

// central.js
module.exports = {
  h: "hello",
  b: "enabled"
}

Import:

// consume.js
const { h, b } = require('./central')

Or alternatively:

// get.js
const central = require('./central')
// central.h
// central.b

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.