I need some help understanding the NodeJs. I'm obviously missing something fundamental. I've got a module similar to the following, using a basic revealing module pattern...
var someArray = [];
var publicApi = {
someArray: someArray,
someFunction: someFunction
};
function someFunction() {
someArray = ['blue', 'green'];
}
module.exports = publicApi;
When I consume this module, someArray is not changed when I call someFunction...
var myModule = require('myModule');
myModule.someFunction();
var test = myModule.someArray;
// test is always an empty array
Please help me understand why. I realize I can probably get this to work using a constructor, but I want to fill the gap in my knowledge of why the above does not work.
Update:
I can get this to work with the following modifications to the module...
var theModule = {
someArray: [],
someFunction: someFunction
};
function someFunction() {
theModule.someArray = ['blue', 'green'];
}
module.exports = theModule;
but I'd still like to understand exactly why the code in the first module did not work. The module I'm working on is fine as a singleton, so I'd love to see what is considered best practice for having variables in a module that can be altered by the functions in that module, and be publicly accessible outside that module.