0

not sure what I'm missing. I have module 2 requiring a variable from module 1. However, when this variable changes the variable doesn't update in module 2 even after deleting the cache.

Example Mod1

var num = 6

function changeNum(){
  num = 60
  print();
}


function print(){
  console.log(num) // this returns 60
}

setTimeout(changeNum, 3000); //change the num value to 60 after 3s

module.exports = num

Mod2

//Tried to use this function to always delete the cache to get the variable anew every time.
//num still returns 6 when console.logged after 3s

function requireUncached(module) {
    delete require.cache[require.resolve(module)];
    return require(module);
};

var num = requireUncached('./mod1.js')

//Also tried this to refresh the value every 1s but it still always returns 6
async function refreshRequire(){
  delete require.cache[require.resolve('./mod1.js')];
  num = require('./mod1.js')
  console.log(num)
  await new Promise(resolve => setTimeout(resolve, 1000));
  refreshRequire();
}
refreshRequire();

I've seen a lot of people ask about this and deleting the cache seems to be the way to get updated variables but I'm not sure why it isn't working here.

  • Nuances of this cache invalidation approach are discussed [here](https://stackoverflow.com/questions/9210542/node-js-require-cache-possible-to-invalidate). – Wyck Jul 05 '21 at 18:33
  • Ah so after reading through that again I think I understand. The problem was that when I refresh the cache it is basically reloading the module afresh, in which case it gets the original defined value for num again as in this refreshed version the function to change num hasn't executed yet. – Dave's a Beginner Jul 05 '21 at 19:46

1 Answers1

0

When you write module.exports = num in Mod1, you are not exporting a reference to the variable num, but instead you are exporting the value that num holds at that moment (i.e. the number 6).

To do what you want, you could export a function instead:

// Mod1
// ...
module.exports = () => num;

and in module 2 retrieve the value of num as follows:

// Mod2
const getNum = require('Mod1');
const num = getNum();

I suggest using the function approach, but if you really want to export a reference to an internal variable, that variable needs to be an object.