0

I am trying to do a simple thing which is obvious I believe in the code below:

module.exports = function(req, res, next) {
    var dop = require('../../config/config').DefaultOptions;
    console.log(require('../../config/config').DefaultOptions);
    console.log(dop);
    dop.firstPage = 'test.sjs';
    next();
};

This is an Expressjs middle ware which is very simple but the interesting point is that next time I load a page both of the console.log results has been changed to 'firstPage: test.sjs'. It shouldn't act like this and it should only change the dop variable.

Anyone with the knowledge why this creepy thing is happening?

Thank you

Shadow4Kill
  • 178
  • 1
  • 9
  • assuming the value concerned is an object, then `dop` becomes a reference to that same object, and any change you make to it affects the original one as well – Robin Zigmond Mar 01 '19 at 15:47
  • Is there anyway to avoid it? Like making ```dop``` standalone. – Shadow4Kill Mar 01 '19 at 15:49
  • yes, see [this question](https://stackoverflow.com/questions/728360/how-do-i-correctly-clone-a-javascript-object). Although your `dop` is a local variable only so whatever you're trying to do by setting it, you won't then be able to observe outside of this function. – Robin Zigmond Mar 01 '19 at 15:51
  • Thank you. Yes ```dop``` is local here because I simplified it to post it here. – Shadow4Kill Mar 01 '19 at 15:53

1 Answers1

0

The main issue is require() is cached, so require('../../config/config') returns reference to the same instance, and as a result changing in one place causes all other references and subsequent requires to get that modified instance.

The simplest solution would be have a function in config to return a config object, that way every time invoking the get config function you will get a new instance with essentially the same content. I.e.:

config.js:

module.exports = {
  getDefaultOptions: function(){
    return {foo: 'bar', ip: '1.1.1.1'}
  }
};
Eric Wong
  • 1,388
  • 7
  • 17