Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if the current npm package is global?

Tags:

node.js

npm

I want to write some code that will be executed on npm postinstall only if the package is installed globally. Is there a built-in solution to detect if the active package is installed globally?

If not then what is the best workaround that will work on any OS? My only idea currently is to check the current working directory of the package and check if its under the global npm path.

like image 931
Zoltan Kochan Avatar asked Jun 25 '15 20:06

Zoltan Kochan


2 Answers

I've found the solution that I was looking for in this repo.

The solution is to check !!process.env.npm_config_global in the postinstall script. That environment variable will be true only if the package was installed globally.

like image 130
Zoltan Kochan Avatar answered Oct 05 '22 11:10

Zoltan Kochan


You could use require.resolve() to give you the path. And you can compare the given path to see if it's installed localy, or globally. You can use npm root -g to get the path of the global modules.

https://nodejs.org/api/globals.html#globals_require_resolve

like image 45
Hyo Byun Avatar answered Oct 05 '22 12:10

Hyo Byun