Grateful Grateful - 1 year ago 142
Node.js Question

Doesn't npm install check for a global version first?

I just setup a test, and tried to

npm install express
even though
already exists globally on my system. To my surprise, instead of using the global version, it ended up re-installing a version locally!? Isn't it supposed to use the global version... Or am I suppose to use
every time, even when I only want to use the existing global version. Otherwise, what's the point of installing anything locally!?

Answer Source

The answer is "NO". It isn't supposed to use your global version.

If you want to use your global version, then you doesn't need to execute npm install at all because it is already installed.

If you do it then, obviously, you are saying "I want to install it locally to my project". And more than that: "I want to install its latest version unless it is declared in my package.json with other explicitly specified version".

In fact, the actual question is: Why in the hell would you want to not install a dependency of your project locally? To have more version mismatch issues?

As @anshuman_singh says, best practice is to always do an npm install --save.

You are able to use globally installed packages, of course. It could be handy for fast testing code that you will drop just after a few hours or so.

But, anyway: If you doesn't have really hard disk or network bandwidth issues, installing all dependencies locally will avoid you too much trouble in the future.

On the other hand, uploading that modules to your code repository is also a bad idea (maybe that is what you were trying to avoid) because, with different versions of node, most native modules won't work if not rebuild. But most VCS support ignoring files and or directories that must not be uploaded.

For example, in git (.gitignore file):


In summary:

  • npm init (if you didn't already it).
  • npm install --save for all your project dependencies.
  • npm install --save-dev for dependencies not needed in production (testing stuff).
  • Don't upload node_modules to your VCS.
  • After new checkout: npm install or npm install --production (to not install dev-dependencies).
  • npm install -g only for tools you will use in console.

This way, you are sure that you will have in production (or other dev environments) the exact same version of each package.

And, finally, if you ever want to upgrade some package to its latest version, simply run:

npm install --save <pagkage_name>@latest.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download