I am working on a node.js application that is intended to be globally installed using npm. I am using commander in order to expose multiple commands to the command line. i.e. my-app serve
and my-app clean
. The problem I'm running into is that there is some data that I want all of my JS files in my lib
directory to have access to, however from what I can tell, I should be avoiding the global
object.
Here is the solution I came up with:
In my lib
directory, I have a file named shared-state.js
. Its contents:
var initialized = false;
var SHAREDSTATE = module.exports = {
init: function( stateToShare ) {
if ( !initialized ) {
SHAREDSTATE.data = stateToShare;
initialized = true;
} else {
// log warning about calling init > 1 time
}
return SHAREDSTATE;
}
};
As long as I call init during my application's start-up, I can write the following code to get access to the shared data.
var sharedState = require('./shared-state').data;
This is a distilled example to illustrate the pattern I am following. In reality I am taking steps to make the data read-only for any modules that are consuming it, and I am appropriately handling the case where init is called multiple times.
My question is this: Am I crazy for going to these lengths to avoid the global
object? Is this an established pattern in node? What is it called? If it is not, how are other people solving a similar issue?