0

I have a variable in my server.js, lets call it 'a'. When I require a module, it doesn't have access to the variable a. For example:

server.js

myModule = require('./myModule.js');
var a = 'Hello!'
myModule.say();

myModule.js

exports.say = function () {
    console.log(a);
}

How can I make it so myModule.js can access the variables in server.js without having function arguments?

  • Check that one: http://stackoverflow.com/questions/3919828/share-variables-between-modules-in-javascript-node-js – Rami Sep 24 '13 at 00:49
  • Well that shows how to access variables in the module from the main app. I'm trying to figure out how to access variables from the app in the module. –  Sep 24 '13 at 00:53
  • `global` is shared throughout the entire application. If you don’t like that, you can also assign to the module/use `module.exports`, or pass the important things to an initialization function, or represent the entire module with a class that takes options, or… – Ry- Sep 24 '13 at 00:56

1 Answers1

0

server.js:

myModule = require('./myModule.js');
global.a = 'Hello!'
myModule.say();

myModule.js:

exports.say = function () {
    console.log(global.a);
}

However, please keep in mind globals are usually discouraged in Node.js (and JavaScript in general). Isn't the point of a module to encapsulate certain functionality? If so, it shouldn't depend on outside variables existing or being defined.

Ideally, you want to pass in the required information into the module via some sort of initialization function or configuration parameters.

Mike Christensen
  • 88,082
  • 50
  • 208
  • 326