Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
468 views
in Technique[技术] by (71.8m points)

node.js - Clearing require cache

I am trying to delete a module from cache as suggested here.

In the documentation we read:

require.cache

  • Object

Modules are cached in this object when they are required. By deleting a key value from this object, the next require will reload the module.

So, I created a file named 1.js that contains a single line:

module.exports = 1;

Then I require it via node shell:

ionicabizau@laptop:~/Documents/test$ node
> require("./1")
1
> require.cache
{ '/home/ionicabizau/Documents/test/1.js': 
   { id: '/home/ionicabizau/Documents/test/1.js',
     exports: 1,
     parent: 
      { id: 'repl',
        exports: [Object],
        parent: undefined,
        filename: '/home/ionicabizau/Documents/test/repl',
        loaded: false,
        children: [Object],
        paths: [Object] },
     filename: '/home/ionicabizau/Documents/test/1.js',
     loaded: true,
     children: [],
     paths: 
      [ '/home/ionicabizau/Documents/test/node_modules',
        '/home/ionicabizau/Documents/node_modules',
        '/home/ionicabizau/node_modules',
        '/home/node_modules',
        '/node_modules' ] } }
# edited file to export 2 (module.exports = 2;)
> require.cache = {}
{}
> require.cache
{}
> require("./1") // supposed to return 2
1

So, why does require("./1") return 1 when my file contains module.exports = 2 and the cache is cleared?

Doing some debugging I saw that there is a Module._cache object that is not cleared when I do require.cache = {}.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

require.cache is just an exposed cache object reference, this property is not used directly, so changing it does nothing. You need to iterate over keys and actually delete them.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...