Search code examples
javascriptnode.jsrequirejses6-modulesjavascript-import

Does require in javascript/nodejs executes same file everytime it is imported in another modules?


Does require() in JavaScript/Node.js executes the same file every time it is imported into other modules?

If yes, how can I have one array in one file and append/update values in it from another JS file? For example, I have an Array in one file and I am updating the Array from multiple files and I want all of them to interact with only the updated array. How can I achieve this?


Solution

  • 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.