Explain Codes LogoExplain Codes Logo

Where does npm install packages?

javascript
npm
package-management
node-modules
Anton ShumikhinbyAnton Shumikhin·Sep 29, 2024
TLDR

Local Install: npm automatically places packages into the ./node_modules directory of your active project.

One might say it's a package's local habitat:

./node_modules/your-package/ 

Global Install: For global installations, npm install -g your-package is your go-to command. To find the path, npm root -g is at your service.

Like a universal dictionary:

  • Unix systems, it's typically at /usr/local/lib/node_modules
  • Windows systems, you'd usually find it in C:\Users\YOURUSERNAME\AppData\Roaming\npm\node_modules

npm list and npm list -g list locally and globally installed packages respectively.

Locating bins

Curious about where npm keeps the executable files for your packages? Say no more:

  • Local bin: npm bin unveils the directory for locally installed package executables.
  • Global bin: Simply add -g as in npm bin -g for globetrotting executables.

Permissions and Unix

Encountered permission issues on Unix systems? Buckle up:

  • Ditch sudo: use a node version manager like nvm or n to bypass the need for sudo with global installations.
  • Global permissions: If need be, shift ownership of your global node_modules directory. Doesn't hurt to have some control, does it?

Customizing npm

Make npm work for you with these simple adjustments:

  • Change global path: Set a new global installation path using npm config set prefix /new/path.
  • Current global path: Verify the existing installation directory with npm config get prefix. Knowledge is power!

Exploring node_modules

Navigating the node_modules structure:

  • Dependency tree: Each package holds its own node_modules folder with dependencies. Kind of like a family tree!
  • Flattened node_modules: From npm v3, the dependency tree is as flat as a pancake, reducing depth.
  • Avoiding duplicates: Flattening prevents version duplication by trying to keep a single version of a package.

Resolving conflicts

Two packages, two conflicting versions of the same dependency, one headache? npm has your back:

  • Nested dependencies: npm nests conflicting versions to ensure each package gets its right mate.
  • Semver resolution: npm uses semantic versioning to determine the acceptable version range for each dependency.

Empower your disk efficiency with npm's built-in linking features:

  • npm link: Symlink a package folder to mimic global installation and ease development. It's like teleportation in the npm world!
  • Local linking: Link local packages together to test changes in real time - because who likes to wait?