Global variables for node.js standard modules? Global variables for node.js standard modules? javascript javascript

Global variables for node.js standard modules?


You could just have a common module.

common.js:

Common = {  util: require('util'),  fs:   require('fs'),  path: require('path')};module.exports = Common;

app.js:

var Common = require('./common.js');console.log(Common.util.inspect(Common));


Each module is supposed to be independent. The require doesn't cost anything anyways after the first one for each module.

What if you wanted to test one module alone? You'd be having a lot of issues because it wouldn't recognize some "global" requires that you have in your app.

Yes, globals are bad, even in this case. Globals almost always ruin: testability, encapsulation and ease of maintenance.

Updated answer Jan. 2012

The global object is now a global inside each module. So every time you assign to a global variable (no scope) inside a module, that becomes part of the global object of that module.

The global object is therefore still not global, and cannot be used as such.

Updated Dec. 2012

The global object now has the global scope within the application and can be used to store any data/functions that need to be accessed from all modules.


global.util = require('util');

There's a section about global objects in the node documentation.

However, globals should be used with care. By adding modules to the global space you reduce testability and encapsulation. But there are cases where using this method is acceptable. For example, I add functions and objects to the global namespace to use within my unit test scripts.