2010
03.14

Scope is a little different in NodeJS but only in a artificial sense. let’s dive into a quick example of what i mean.

Circle.js

  var PI = 3.14;
  exports.getPi = functon() {
    return PI;
  }

If you were to include this file into a browser you would expect to be able to access the variable PI from another file (ignoring the syntax error which would be created by assigning to the undefined object “exports”). This is not the case in NodeJS, when you call require to include this script the contents of the file is inserted into a function as follows…

    var wrapper = "(function (exports, require, module, __filename, __dirname) { "
                + content
                + "\n});";

By calling this wrapper function and passing in an object to the exports parameter, your exported variables/functions are added to the exports object which is then returned as a result of a “require” call.

Because your exported functions are defined inside another function (the one generated when the script is imported) any variables (like PI) are still accessible by your exported functions due to JavaScripts normal scoping. Take a look at JavaScript closures for more information.

Conclusion

  • Each script can access what you “require” into it and what you define in it.
  • Requires are cached so every call to require for the same module should get a reference to the same thing
  • Finally this is my current understanding, ill update as i learn, if you can enlighten me any further leave me a message

No Comment.

Add Your Comment