Anytime you install a package using NPM, the package files and data will be saved as a
.tar file in the NPM cache folder (automatically configured during installation) to be reused later when you run the same
npm install command.
Your NPM cache files will be stored under
~/.npm/_cacache folder by default.
By utilizing a cache, NPM will not download the same package from the internet and would extract the
.tar file from your cache to your current working directory instead.
With cached files, NPM will optimize the number of downloads and internet usage for you.
But since NPM won’t remove data by itself, the cache size will only grow as you install new packages to your local computer.
For example, after 9 months of using a new laptop, I found my NPM cache size has grown to 705 MB.
This is why you may want to clear your NPM cache files: you want to clean up packages that you know you’re not going to require anymore, including older versions of your dependencies, and reclaim your disk space.
Now before cleaning your cache, you may want to verify the cache with
npm cache verify command first to see how big the cache size is:
$ npm cache verify Cache verified and compressed (~/.npm/_cacache) Content verified: 12616 (705806589 bytes) Content garbage-collected: 5216 (477566290 bytes) Index entries: 20993 Finished in 107.121s
Note that the verification process might take quite a long time depending on the size of your cache.
Now that I know my cache size is 705806589 bytes or 705 MB, I will clean the cache using
npm clean cache --force command.
$ npm clean cache --force
clean cache command will look for the
package.json file in the current directory where you run the command.
At first, I thought it will only clear the cache from
dependencies listed in a
package.json file, but after running the command, I found all cached files have been removed completely.
clean cache command finished running, you can run
npm verify cache again to look at the cache size.
The following shows my verified cache content has been cleared completely:
$ npm cache verify Cache verified and compressed (~/.npm/_cacache) Content verified: 0 (0 bytes) Index entries: 0 Finished in 0.008s
And that’s how you can clear the NPM cache 😉
For further information about NPM cache, you can see the documentation here.
The NPM cache system provides you with a way to save internet data usage by saving the package data and reuse it when you install the same package again.
Since NPM version 5, the NPM cache system has been improved so that it can self-heal and resist data corruption issues.
This way, you won’t have to clear your cache for any corrupted data issues. The only reason you want to clear your cache is because the size has grown so big over a long period of time, so you need to reclaim the disk space.