Home > Mobile >  Why doesn't setting NodeJS module cache to false get NodeJS to reload module?
Why doesn't setting NodeJS module cache to false get NodeJS to reload module?

Time:05-15

I have 2 files, one named one.js and other name first.js.
one.js

var first = require("./first.js")
require.cache[first.module.id].loaded=false
require("./first.js")

first.js

console.log("First is running");
module.exports={module}

It's output is:

First is running

and not

First is running
First is running

as I expected. Why is it that even though I set the loaded property of the first.js module to false, it is still not being reloaded?

CodePudding user response:

You have to remove the cached module from the require.cache object to force node to load the module again. Node won't execute the module as long as it is in the require.cache.

One way to delete the module from the cache is shown below:

delete require.cache[require.resolve("./first.js")];
  • Related