There aren’t many (good) use-cases for this, but if you ever need to un-require a module from NodeJS you can do it using the following code:

var path = "full path to module";

if (require.cache[path]){

  delete require.cache[path];


The important thing to note here is that you’re not referencing the module in the same manner that you included it. For example, if we wanted to bring in Mocha and then un-require it, the following code would not work:

var path = "mocha";

var mocha = require(path);

if (require.cache[path]){

   //never gets here delete require.cache[path];


Instead you’ll find the path in the cache to be something like “/node_modules/mocha/lib/mocha.js”. That’s one of the many reasons why using this technique in production is probably not a good idea.

That being said, it can be done.

  1. alex-js posted this