Zoltan Kochan
Zoltan Kochan

Reputation: 7596

How to detect if the current npm package is global?

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.

Upvotes: 6

Views: 1231

Answers (2)

Zoltan Kochan
Zoltan Kochan

Reputation: 7596

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.

Upvotes: 7

Hyo Byun
Hyo Byun

Reputation: 1276

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

Upvotes: 1

Related Questions