index.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*!
  2. * global-prefix <https://github.com/jonschlinkert/global-prefix>
  3. *
  4. * Copyright (c) 2015-present Jon Schlinkert.
  5. * Licensed under the MIT license.
  6. */
  7. 'use strict';
  8. const fs = require('fs');
  9. const os = require('os');
  10. const path = require('path');
  11. const ini = require('ini');
  12. let prefix;
  13. const getPrefix = () => {
  14. if (process.env.PREFIX) return process.env.PREFIX;
  15. if (prefix) return prefix;
  16. // Start by checking if the global prefix is set by the user
  17. let home = os.homedir();
  18. // os.homedir() returns undefined if $HOME is not set; path.resolve requires strings
  19. if (home) {
  20. prefix = tryConfigPath(path.resolve(home, '.npmrc'));
  21. }
  22. if (prefix) {
  23. return prefix;
  24. }
  25. // Otherwise find the path of npm
  26. let npm = tryNpmPath();
  27. if (npm) {
  28. // Check the built-in npm config file
  29. prefix = tryConfigPath(path.resolve(npm, '..', '..', 'npmrc'));
  30. if (prefix) {
  31. // Now the global npm config can also be checked.
  32. prefix = tryConfigPath(path.resolve(prefix, 'etc', 'npmrc')) || prefix;
  33. }
  34. }
  35. if (!prefix) {
  36. let { APPDATA, DESTDIR, OSTYPE } = process.env;
  37. // c:\node\node.exe --> prefix=c:\node\
  38. if (process.platform === 'win32' || OSTYPE === 'msys' || OSTYPE === 'cygwin') {
  39. prefix = APPDATA ? path.join(APPDATA, 'npm') : path.dirname(process.execPath);
  40. return prefix;
  41. }
  42. // /usr/local/bin/node --> prefix=/usr/local
  43. prefix = path.dirname(path.dirname(process.execPath));
  44. // destdir only is respected on Unix
  45. if (DESTDIR) {
  46. prefix = path.join(DESTDIR, prefix);
  47. }
  48. }
  49. return prefix;
  50. }
  51. function tryNpmPath() {
  52. try {
  53. return fs.realpathSync(require('which').sync('npm'));
  54. } catch (err) { /* do nothing */ }
  55. }
  56. function tryConfigPath(configPath) {
  57. try {
  58. return ini.parse(fs.readFileSync(configPath, 'utf-8')).prefix;
  59. } catch (err) { /* do nothing */ }
  60. }
  61. /**
  62. * Expose `prefix`
  63. */
  64. Reflect.defineProperty(module, 'exports', {
  65. get() {
  66. return getPrefix();
  67. }
  68. });