简体   繁体   中英

NodeJS Caching issue

I am aware that Nodejs caches required files.

I have created a sites directory for the sole purpose of storing configuration files. I want to grab a dynamically named configuration file.

router.get('/:site?', function(req, res, next) {

    var site = (req.params && req.params.site) || 'default';

    var env = process.env.NODE_ENV,
        vaildEnv = ['development', 'staging', 'production'];

    if(vaildEnv.indexOf(env) === -1) env = 'default';

    var curDir = __dirname,
        siteDefaultConfigPath = curDir + '/../sites/' + env + '/default.js',
        siteConfigPath = curDir + '/../sites/' + env + '/' + site + '.js',
        siteDefaultConfig, siteConfig;

    if(!fs.existsSync(siteConfigPath)) return next();

    siteConfig = require(siteConfigPath);

    if(site !== 'default') {
        if(fs.existsSync(siteDefaultConfigPath)) {
            siteDefaultConfig = require(siteDefaultConfigPath);
            siteConfig = _.extend(siteDefaultConfig, siteConfig);
        }
    }
}

Now if I try to access http://website.com/ then it correctly fetches the default.js file. If I try accessing http://website.com/test then again it correctly fetches test.js file. But now if I try access http://website.com/ again then it still shows the test.js file! Not sure what is happening here. I even tried to console.log(siteConfigPath) and it shows the path to the correct file every time.

More interestingly, if I visit http://website.com/test and then and other URL like http://website.com/testing it always returns the correct file. It's only the http://website.com/ URL that shows the cached results.

Any help is appreciated.

The issue is this:

siteDefaultConfig = require(siteDefaultConfigPath);
siteConfig = _.extend(_.clone(siteDefaultConfig), siteConfig);

You are permanently extending the object returned from require(siteDefaultConfigPath), so on subsequent requests, that object will no longer be the original object, but will instead return the extended version.

You need to clone the object returned from require(). You have a few alternatives, if it is a shallow object (no nested objects) you can use underscore's clone method:

siteDefaultConfig = _.clone(require(siteDefaultConfigPath))

However if you do have nested objects, you can try this approach:

siteDefaultConfig = JSON.parse(JSON.stringify(require(siteDefaultConfigPath)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM