简体   繁体   中英

Difference between ~/.npm, $PROJECT/node_modules, and /usr/lib/node_modules?

I installed npm and when I did my first sudo npm install some-package -g it installed that package to /usr/lib/node_modules as I expected, but then it also created several files in ~/.npm. What's the difference between these locations?

Other answers here have said that a global installation using -g should install it to your home directory by default, but for me it installs it to /usr/lib/node_modules, am I doing something wrong?

And when I do a local installation without -g it installs to the current directory $PROJECT/node_modules. What's the difference between all these locations, and what should go where?

The system wide package install directory, typically under /usr/lib is usually used for globally installed packages that provide a binary which should be available in your PATH (to be able to execute it from anywhere).

The local install directory node_modules , created by npm install at the location where you're executing npm , is typically located in your project directory and usually used for project specific dependencies.

The ~/.npm contains packages already downloaded. When installing the same package in another location, npm will lookup that package in that cache directory first.

Reference: https://docs.npmjs.com/files/folders

Related files:

  • .npmrc - NPM configurations at different locations
  • package.json - Packages and their versions for a project

Hypothetical scenario: two projects using Grunt (a Javascript based buildscripting tool):

Both projects use different Grunt versions. One project is older. Grunt can't be updated without having to adapt the whole build process, another project has just started.

You have to install "grunt-cli" system wide (using the -g flag) since it provides the grunt binary. This CLI binary will lookup for a local "grunt" in your current project directory. The "grunt" npm on the other hand, installed locally (without -g ) will then be bootstrapped by the CLI. When downloading grunt for the first project npm will store downloaded packages in ~/.npm , when installing grunt for the second project, npm will lookup packages common to both projects in ~/.npm first.

There are other reasons to install packages globally, the most time they provide a binary that should be located in your PATH.


Alternatively, some packages that typically need to be installed globally can also be installed locally. You'll then have to add the path to that binary (eg path/to/your/node_modules/.bin/<BINARY> ) to your PATH variable or just specify the full execution path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM