There are situations when some Node.js modules in the application become obsolete and need to be updated to the latest versions.
The command npm install reads the module names and their corresponding versions from package.json file and installs them in node_modules folder. The command does not update any module to latest version.
The command npm update updates all modules present in package.json to their latest versions. It installs the latest versions of modules from the npm repositories while respecting the caret and tilde dependencies specified in the package.json file. However, the most annoying aspect of running the update command is that although the modules are updated to the latest versions, the versions mentioned in the package.json file are not changed. This leads to confusion since there is mismatch between the installed versions in node_modules repository and the versions mentioned in package.json file.
So what is the best way to avoid this discrepancy?
The npm-check-updates utility comes to rescue. First install it by running the following command:
- npm install –g npm-check-updates
Once the utility is installed globally, you can invoke it as follows:
The ncu command is a short form of npm-check-updates and produces the output shown above without changing anything. The above output shows that for ‘express’ the current version installed is ~4.9.0 but the latest version available respecting ~ is 4.15.2. Similarly current version of ‘body-parser’ is ~1.8.1 but the latest version available in npm repositories respecting the ~ is 1.17.1.
The ncu –u command will modify the package.json file with the latest version available in npm repositories. Now if you issue the npm install command, the new versions from the updated package.json file are installed to your local repository.
In summary, if you want to update your node modules to latest versions respecting the semver then it is a two step process.
Step 1: ncu –u
This will update the package.json file as per latest versions available in npm repositories on web.
Step 2: npm install
This will update the local node_modules repository with the versions present in package.json.
This way both the package.json as well as local node_modules repository are updated to latest versions available on web.
This working: npm install npm-check-updates –g
Command “npm install –g npm-check-updates” should be replaced by command” npm install npm-check-updates -g”.
I have npm version 8.3.1