Let say, after I require a module and do something as below:

var b = require('./b.js');
--- do something with b ---

Then I want to take away module b (i.e. clean up the cache). how I can do it?

The reason is that I want to dynamically load/ remove or update the module without restarting node server. any idea?

------- more -------- based on the suggestion to delete require.cache, it still doesn't work...

what I did are few things:
1) delete require.cache[require.resolve('./b.js')];
2) loop for every require.cache's children and remove any child who is b.js
3) delete b

However, when i call b, it is still there! it is still accessible. unless I do that:

b = {};

not sure if it is a good way to handle that. because if later, I require ('./b.js') again while b.js has been modified. Will it require the old cached b.js (which I tried to delete), or the new one?

----------- More finding --------------

ok. i do more testing and playing around with the code.. here is what I found:

1) delete require.cache[]  is essential.  Only if it is deleted, 
 then the next time I load a new b.js will take effect.
2) looping through require.cache[] and delete any entry in the 
 children with the full filename of b.js doesn't take any effect.  i.e.
u can delete or leave it.  However, I'm unsure if there is any side
effect.  I think it is a good idea to keep it clean and delete it if
there is no performance impact.
3) of course, assign b={} doesn't really necessary, but i think it is 
 useful to also keep it clean.
share|improve this question
The variable you assign the result of require('./b') to won't be deleted, the delete operation will only allow you to require a file a second time without getting a cached version but the variable won't magically be updated when you do. – robertklep yesterday
yes.. u r right.. and here is what i find out... (see my edition) – murvinlai yesterday

1 Answer

up vote 1 down vote accepted

You can use this to delete its entry in the cache:

delete require.cache[require.resolve('./b.js')]

require.resolve() will figure out the full path of ./b.js, which is used as a cache key.

share|improve this answer
Oh.. let me try . so the full path will be module.filename? – murvinlai 2 days ago
Just try. I think it is more complicated than just doing delete. doing delete remove the top level cache. However, because b.js is a child of a.js, so it also cached as a child in a.js. So, i think i also need to remove the child of a.js – murvinlai 2 days ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.