node.js require() cache - possible to invalidate?

后端 未结 17 1644
我寻月下人不归
我寻月下人不归 2020-11-22 06:52

From the node.js documentation:

Modules are cached after the first time they are loaded. This means (among other things) that every call to require(\'

17条回答
  •  情深已故
    2020-11-22 07:44

    The solutions is to use:

    delete require.cache[require.resolve()]
    

    Find here some basic explanations for those who, like me, are a bit new in this:

    Suppose you have a dummy example.js file in the root of your directory:

    exports.message = "hi";
    exports.say = function () {
      console.log(message);
    }
    

    Then you require() like this:

    $ node
    > require('./example.js')
    { message: 'hi', say: [Function] }
    

    If you then add a line like this to example.js:

    exports.message = "hi";
    exports.say = function () {
      console.log(message);
    }
    
    exports.farewell = "bye!";      // this line is added later on
    

    And continue in the console, the module is not updated:

    > require('./example.js')
    { message: 'hi', say: [Function] }
    

    That's when you can use delete require.cache[require.resolve()] indicated in luff's answer:

    > delete require.cache[require.resolve('./example.js')]
    true
    > require('./example.js')
    { message: 'hi', say: [Function], farewell: 'bye!' }
    

    So the cache is cleaned and the require() captures the content of the file again, loading all the current values.

提交回复
热议问题