A cache hit

The NPM install or NPM update commands, after downloading compressed packages from Registry, are stored in the local cache directory: ~/.npm/cacache, which has three folders

NPM installs dependencies based on the version,name, and integrity information of the specific package in package-lock. Pacote :range-manifest:{url}:{integrity} generate a unique key, hash the SHA256 hash, go to _cacache/index-v5 and get the basic meta cache. The first four hash bits are used to divide paths. If the dependency information is changed, the generated hash has no corresponding cache information to match, and the cache is downloaded again and updated

The shasum is the hash of the tar package. Use this hash to find the corresponding gzip (TGZ) cache in _cacache/ Content-v2 and decompress the corresponding dependent tar package

Caching mechanisms

When NPM install executes, it first builds the dependency tree and installs each package in the tree in turn.

If there are dependencies in the cache, the remote repository is checked for expiration (304 check), and if expired, the cache is refreshed with the new returned data, otherwise the data in the cache is used directly.

In addition, NPM provides fallback-to-offline mode depending on whether the remote warehouse is offline or has lost access to the target. This mode enables NPM to use the local cache directly in cases where remote repositories cannot be accessed. Whenever offline, NPM falls back into cache as much as possible – rather than insisting on retrying network requests or failing

In addition, new parameters are provided that users can specify the policy to be used by the cache

–prefer-offline: will cause NPM to skip any conditional requests (304 check) and use cached data directly, only accessing the network if the cache cannot match. This will make the process of adding dependency packages to the project much faster.

For example, NPM install express –prefer-offline will now match express in the cache and will only download it online if there is no match in the local cache.

–prefer-online: with it will force NPM to revalidate cached data (using 304 check) and refresh the cache with revalidated fresh data.

— Offline forces NPM to use cache or exit. If anything you try to install is not already in the cache, it will get a code error.

You can set the cache policy using.npmrc or NPM config set.

A new NPM cache Verify command will garbage collect your cache, reduce disk usage for unnecessary items, and perform comprehensive integrity verification for indexes and content.