Modules are cached, if you load them again cached copy is loaded.
https://nodejs.org/api/modules.html#modules_require_cache
Modules are cached in this object when they are required. By deleting
a key value from this object, the next require will reload the module.
This does not apply to native addons, for which reloading will result
in an error.
Adding or replacing entries is also possible. This cache is checked
before native modules and if a name matching a native module is added
to the cache, no require call is going to receive the native module
anymore. Use with care!
You can use https://www.npmjs.com/package/clear-module
const clearModule = require('clear-module');
const myArray = clearModule('./myArray'); // but you need load this everytime to get fresh copy of that array
Instead, you can expose a function from your module to read the array value, so it will fetch a new value always.
myArray.js
const myArray = [1];
const get = () => {
return myArray;
};
const update = (data) => {
myArray.push(data);
};
exports.get = get;
exports.update = update;
index.js
const myArray = require('./myArray');
console.log(myArray.get()); // [1]
console.log(myArray.update(2)); // update the value
console.log(myArray.get()); // [1,2]
So now use myArray.get()
always to read the value and use myArray.update(data)
to update the.