Require a fresh CommonJS module

In rare circumstances you might want to require a Node.js module multiple times and make sure it reflects any changes introduced to the file in the meantime. This turns out to be quite straightforward! As a matter of fact you can invalidate CommonJS cache with a single line of code.

Let's demonstrate the problem using a simple dependency module that just returns the current timestamp.

// dependency.js
module.exports = Date.now() // returns something like: 1597094558720

Now, to prove that module's exported value is being cached, let's try to require it a couple of times and log out the value:

// main.js
setInterval(() => {
  console.log(require('./dependency.js'))
}, 1000)

// will print out the same(cached) value every second
// 1597094558720
// 1597094558720
// 1597094558720
// ...

Module export cache is great for most use cases when performance is a top priority. But not in circumstances when you want to have a responsive system that is able to work with new module versions/instances, without a complete system restart. In those cases a simple function is sufficient to invalidate the cache and require a newly exported value:

// require-fresh.js
module.exports = function requireFresh(modulePath) {
  delete require.cache[require.resolve(modulePath)] // cleanup cache stored under specified require path
  return require(modulePath) // return a new module's export
}

Now if we use requireFresh function instead of the native require, we can keep up with the latest module version, even if the file has been updated in the meantime and the logic has been changed:

// main.js
const requireFresh = require('./require-fresh')

// same as the previous main.js code example, only this time we use "requireFresh" instead of "require"
setInterval(() => {
  console.log(requireFresh('./dependency.js'))
}, 1000)

// we get different values logged out every second
// 1597096147937
// 1597096148939
// 1597096149941
// ...

We've sucessfully invalidated the cache and made the Node.js engine re-evaluate our module :).
Until next time, cheers!