Node: Required json file is not removed from cache, even after a re-install

Created on 12 Oct 2015  路  1Comment  路  Source: nodejs/node

We have this piece of code in our CLI tool:

  function getVersion() {
    return require('../../package.json').version;
  }

A customer experienced an issue where he re-installed a new version of our software via npm, and when he ran it, he saw that he was getting the package version from the older installation.
I can verify from his terminal log that the newer package was installed.
If it makes any difference, it is a globally installed tool.

I can have a workaround by manually deleting it from the cache.

  function getVersion() {
    //fixing Node bug
    var name = require.resolve('../../package.json');
    delete require.cache[name];
    return require('../../package.json').version;
  }

Is this a bug, or an expected behavior?
This was experienced in Node v4.1.2.
I don't know if it affects other versions.

question

Most helpful comment

This is the expected behavior, NOT a bug, if the json file was required at least once before the file was modified in the file system it will use the memcached version next times. In your workaround you are just updating the cache, another solution would be to request the file directly with the fs module and parse it or manage it as you want:

function getVersion() {
    return JSON.parse(fs.readFileSync('/path/to/file.json', 'utf8')).version;
}

>All comments

This is the expected behavior, NOT a bug, if the json file was required at least once before the file was modified in the file system it will use the memcached version next times. In your workaround you are just updating the cache, another solution would be to request the file directly with the fs module and parse it or manage it as you want:

function getVersion() {
    return JSON.parse(fs.readFileSync('/path/to/file.json', 'utf8')).version;
}
Was this page helpful?
0 / 5 - 0 ratings