The NPM cache is a local directory where previously downloaded packages and dependencies are stored.
When we install or update a package, NPM searches its local cache before downloading it from the package registry.
If the package or dependency is already in the cache, that copy is used instead of downloading it again, saving us the wait.
Normally, we shouldn’t have to touch the NPM cache frequently, or almost never. But if you ever have any issues, here’s how to fix it.
Cache Configuration
The configuration of the NPM cache can be customized according to our needs. To access the NPM configuration, we can use the following command:
npm config edit
This will open the NPM configuration file in our default text editor.
Here we can modify different parameters related to the cache, such as the cache storage directory (cache
) and the maximum cache duration (cache-min
).
For example, if we want to change the cache storage directory to a custom directory called “my-cache”, we can add the following line to the configuration file:
cache=my-cache
That said, unless we are very clear about what we are doing, or we have a very rare error that forces us to change it, normally we shouldn’t have to touch this file.
Finally, the NPM cache files are stored in these folders:
%LocalAppData%\npm-cache
on Windows~/.npm
on Linux
But, even more so, normally we should never have to touch the files in these folders “manually.”
Cache Cleaning
As we work with NPM, the cache can accumulate outdated or unnecessary packages and dependencies. To free up disk space, it’s a good idea to perform periodic cleaning.
We can clean the NPM cache using the following command:
npm cache clean
This will remove all packages and dependencies that are not in use, thus freeing up disk space.
Additionally, in some cases, it’s not common but it can happen that the cache gives us issues with some library. Because it’s stuck, or who knows… in that case, cleaning the cache is usually one of the first measures.
If we use the --force
command to force the removal of all items from the cache, regardless of whether they are in use or not.
npm cache clean --force
The cache will be clean, as if NPM was freshly installed. Nothing will get corrupted in any project, nor will anything be lost. Simply, the next time you install a package, it may take a little longer because it will have to download everything.
Cache Verification
The verification of the NPM cache allows us to check if a specific package or dependency is present in the cache before downloading it. To check if a package is in the cache, we can use the following command:
npm cache verify <package-name>
If the package is in the cache, NPM will display a message confirming its presence. Otherwise, NPM will download the package from the registry.