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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With