node.js require() cache - possible to invalidate?

后端 未结 17 1851
我寻月下人不归
我寻月下人不归 2020-11-22 06:52

From the node.js documentation:

Modules are cached after the first time they are loaded. This means (among other things) that every call to require(\'

17条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 07:31

    Yes, you can access the cache via require.cache[moduleName] where moduleName is the name of the module you wish to access. Deleting an entry by calling delete require.cache[moduleName] will cause require to load the actual file.

    This is how you would remove all cached files associated with the module:

    /**
     * Removes a module from the cache
     */
    function purgeCache(moduleName) {
        // Traverse the cache looking for the files
        // loaded by the specified module name
        searchCache(moduleName, function (mod) {
            delete require.cache[mod.id];
        });
    
        // Remove cached paths to the module.
        // Thanks to @bentael for pointing this out.
        Object.keys(module.constructor._pathCache).forEach(function(cacheKey) {
            if (cacheKey.indexOf(moduleName)>0) {
                delete module.constructor._pathCache[cacheKey];
            }
        });
    };
    
    /**
     * Traverses the cache to search for all the cached
     * files of the specified module name
     */
    function searchCache(moduleName, callback) {
        // Resolve the module identified by the specified name
        var mod = require.resolve(moduleName);
    
        // Check if the module has been resolved and found within
        // the cache
        if (mod && ((mod = require.cache[mod]) !== undefined)) {
            // Recursively go over the results
            (function traverse(mod) {
                // Go over each of the module's children and
                // traverse them
                mod.children.forEach(function (child) {
                    traverse(child);
                });
    
                // Call the specified callback providing the
                // found cached module
                callback(mod);
            }(mod));
        }
    };
    

    Usage would be:

    // Load the package
    var mypackage = require('./mypackage');
    
    // Purge the package from cache
    purgeCache('./mypackage');
    

    Since this code uses the same resolver require does, just specify whatever you would for require.


    "Unix was not designed to stop its users from doing stupid things, as that would also stop them from doing clever things." – Doug Gwyn

    I think that there should have been a way for performing an explicit uncached module loading.

提交回复
热议问题