6

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.

Zoltan Kochan
  • 5,180
  • 29
  • 38
  • http://stackoverflow.com/questions/26104276/how-to-tell-if-npm-package-was-installed-globally-or-locally – danronmoon Jun 25 '15 at 21:04
  • Yeah, maybe I can call the `npm list -g` command programatically and check if my package is in the list. Although I would prefer a different solution – Zoltan Kochan Jun 25 '15 at 21:12

2 Answers2

7

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.

Zoltan Kochan
  • 5,180
  • 29
  • 38
1

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

Hyo Byun
  • 1,196
  • 9
  • 18
  • 2
    What would you compare it to? If you use something like [nvm](https://github.com/creationix/nvm) for example, the global module location is different than normal. – CatDadCode Jun 25 '15 at 21:05
  • I have now another idea. I am thinking about whether I can get somehow the args that were used when installing the package. In that case I would be able to check if there was -g option – Zoltan Kochan Jun 25 '15 at 21:10
  • 1
    `npm root -g` will give you the global module locaiton – Hyo Byun Jun 25 '15 at 21:18