como-gestionar-gestion-cache-npm

How to manage the NPM cache

  • 3 min

The NPM cache is a local directory where downloaded packages and dependencies are stored.

When we install or update a package, NPM first checks 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 don’t need to touch the NPM cache frequently, if ever. But if you ever have a problem, here’s how to fix it.

Cache Configuration

The NPM cache configuration 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 various parameters related to the cache, such as the cache storage directory (cache) and the maximum cache lifetime (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

As said, unless we are very clear about what we are doing, or have a very strange error forcing us to change it, normally we don’t need to touch this file.

Finally, the NPM cache files are stored in these folders:

  • %LocalAppData%\npm-cache on Windows
  • ~/.npm on Linux

But here, even more so, normally we should never have to touch the files in these folders “manually.”

Cache Cleanup

As we work with NPM, the cache can accumulate obsolete or unnecessary packages and dependencies. To free up disk space, it doesn’t hurt to perform periodic cleanup.

We can clean the NPM cache using the following command:

npm cache clean

This will delete all packages and dependencies that are not in use, thus freeing up disk space.

Furthermore, in some cases, it’s not frequent but it’s possible that the cache causes problems with some library. Because it got stuck, or who knows… in that case, cleaning the cache is usually one of the first measures.

We can use the --force command to force the deletion of all cache items, regardless of whether they are in use or not.

npm cache clean —force

The cache will be clean, as if NPM was just installed. Nothing in any of your projects will be corrupted or lost. Simply, the next time you install a package, it might take a tiny bit longer because it will have to download everything.

Cache Verification

NPM cache verification allows us to check if a specific package or dependency is in the cache before downloading it. To verify if a package is in the cache, we can use the following command:

npm cache verify

If the package is in the cache, NPM will display a message confirming its presence. Otherwise, NPM will download the package from the registry.