Shane
Shane

Reputation: 368

Node.js Global Variables and using Require

Many people have suggested using "modules" that "export" an object, so that you can bring in variables to another file - because once you require a certain file name once, all future calls in other files to require that same file will immediately return the SAME exported object that was given the first time that file was required without reevaluating any code. This allows you to choose by requiring files which variables you want to share between files without using global, which is essential to maintaining state between files or split up code which needs to use the same variables.

My problem is: How can you modify those exported variables - or are they unchangeable - and if they are unchangeable then they are lacking functionality that you can only achieve using global variables... ?

Upvotes: 0

Views: 1440

Answers (1)

nponeccop
nponeccop

Reputation: 13677

There are no such things as exportable variables. The require function returns a usual Javascript object, and things you call "exported variables" are just properties of that returned object.

Internally, require() maintains a dictionary mapping module identifiers to these objects and guarantees that the same object is returned for the same module identifiers passed to it.

So you can modify those properties how you want. You can even do things like this:

var connect = require('connect')
connect.foo = 42

This code will effectively monkey-patch connect module and add foo "export" to it.

Upvotes: 1

Related Questions