Search code examples
javascriptnode.jswebmean-stackmeanjs

Mean Stack - can using a "Globals" module cause issues when werving a web app?


I have a variable (a constructed filename) that I need to get from within an API in one file to be stored as a variable in another file.

The way my code is set up, there's not really a way (that I can think of) to get this variable from one file to another without using globals. I've been looking around at a few different methods and decided to create a globals module (globals.js):

var globals = {
    'new_img': ''
}

module.exports = globals;

I've written:

var globals        = require('./public/js/globals');

In my server.js and in my routes.js so that all of my API's and controllers have access to this module.

When I serve this web application and multiple people have their own instances of the webpage, will they all be using the same globals module? This is not my desired effect. What would be better ways of going about this?


Solution

  • yes they will be using the same instance.

    That pattern is a singleton, you're exporting and making global a variable, the same spot in memory will be visibile by the whole app.

    With the help of the debugger you can analyze the require code in depth and see that Nodejs will cache the result of that call and return the same instance everytime.

    NodeJS source code:

    enter image description here enter image description here

    if your desired result is to have different instances you can shallow clone the object.

    var globals  = _.extend({}, require('./public/js/globals')); //ecma5 + underscore.js
    
    var globals = Object.assign({}, require('./public/js/globals')); //ecma6