Where does npm install the packages?

By

Learn where npm installs your packages, in the local node_modules folder for a normal install and in a global location you can find with npm root -g.

~~~

npm installs packages in the node_modules folder of your current project. With the -g flag, it installs them in a single global location instead, and npm root -g tells you where that is on your machine.

Let’s look at both cases in detail.

Read the npm guide if you are starting out with npm, it’s going to go in a lot of the basic details of it.

When you install a package using npm (or yarn), you can perform 2 types of installation:

Where do local installs go?

By default, when you type an npm install command, like:

npm install lodash

the package is installed in the current file tree, under the node_modules subfolder. If that folder doesn’t exist yet, npm creates it.

As this happens, npm also adds the lodash entry in the dependencies property of the package.json file present in the current folder.

You can ask npm for the exact path with:

npm root
/Users/flavio/dev/twitter-clone/node_modules

If the package provides an executable command, npm puts it in node_modules/.bin. That’s why you can run locally installed tools with npx, like npx eslint, without installing them globally.

Where do global installs go?

A global installation is performed using the -g flag:

npm install -g lodash

When this happens, npm won’t install the package under the local folder. It uses a global location instead, shared by every project on the machine.

Where, exactly? The npm root -g command will tell you:

npm root -g

On macOS or Linux this location could be /usr/local/lib/node_modules. On Windows it could be C:\Users\YOU\AppData\Roaming\npm\node_modules

If you use nvm to manage Node.js versions, however, that location differs. Mine, for example, was /Users/flavio/.nvm/versions/node/v8.9.0/lib/node_modules.

Which one should you use?

My advice is to install locally whenever the package is part of a project. Local installs are listed in package.json, so anyone cloning the project gets the same setup with a single npm install.

Global installs make sense for command line tools you use across projects, things you invoke from the terminal rather than import in code.

A common pitfall

If you installed Node.js with the official installer on macOS or Linux, a global install can fail with an EACCES permission error, because the global folder is owned by the system.

Don’t reach for sudo npm install -g. Use a version manager like nvm instead: it puts the global folder inside your home directory, and the permission errors disappear.

Tagged: Node.js · All topics
~~~

Related posts about node: