Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does npm install local packages in my home directory?

Tags:

node.js

npm

Node.js newbie here, Windows 10. I npm install-ed some packages (without -g) while inside a directory that didn't have package.json. npm placed the packages in C:\Users\{MyName}\node_modules\.

Now I'm seeing some weird behavior:

  • When I'm in my project directory (has package.json but no node_modules/ yet), npm list and npm list -g both show an empty list
  • When I'm in a non-project directory (no package.json)...
    • npm list -g still shows an empty list
    • However, npm list shows everything in C:\Users\{MyName}\node_modules\

Question 1. What is going on here? Apparently, npm's default global path should be C:\Users\{MyName}\AppData\Roaming\npm\. If so, why is it using C:\Users\{MyName}\node_modules\?

Question 2. How do I get out of this mess? Node.js has no problem importing packages from C:\Users\{MyName}\node_modules\, but I want npm to list them properly. How can I delete the semi-global packages, reinstall them correctly, and ensure that this doesn't happen again?

like image 718
Phil Kang Avatar asked Jun 17 '18 07:06

Phil Kang


People also ask

Where does npm install local packages?

Local Installation of Packages: Local packages are installed in the directory where you run npm install <package-name> and they are put in the node_modules folder under this directory.

Does npm install locally by default?

It's best to install locally when relying on a package from your module, such as Node. js. This is how npm install works by default. The grunt CLI package, for example, must be installed globally before it can be used as a command-line tool.

Should I install npm packages globally or locally?

In general, all packages should be installed locally. This makes sure you can have dozens of applications in your computer, all running a different version of each package if needed.


2 Answers

Welp, turns out I've been mistakenly npm install-ing packages without package.json. The first time I did this, I was in my home directory(C:\Users\{MyName}\). This caused npm to create node_modules/ and package-lock.json in the home directory. Further (mistaken) attempts to install packages in my projects--which were still missing package.json--caused npm to traverse upwards, until it found the initial node_modules/ dir, and install everything there. Because my home directory is among the places Node.js looks for modules, I didn't notice my mistake until now. :P

like image 184
Phil Kang Avatar answered Nov 15 '22 12:11

Phil Kang


Not sure why it’s doing it, but the way to avoid it is to initialize your project directory using:

npm init

or if you don’t want to answer the questions:

npm init -y

That will setup the directory with the package.json and node_modules will be put there.

like image 29
user2771365 Avatar answered Nov 15 '22 10:11

user2771365