Keine Beschreibung

index.js 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*!
  2. * global-prefix <https://github.com/jonschlinkert/global-prefix>
  3. *
  4. * Copyright (c) 2015-2017 Jon Schlinkert.
  5. * Licensed under the MIT license.
  6. */
  7. 'use strict';
  8. var fs = require('fs');
  9. var path = require('path');
  10. var expand = require('expand-tilde');
  11. var homedir = require('homedir-polyfill');
  12. var ini = require('ini');
  13. var prefix;
  14. function getPrefix() {
  15. if (process.env.PREFIX) {
  16. prefix = process.env.PREFIX;
  17. } else {
  18. // Start by checking if the global prefix is set by the user
  19. var home = homedir();
  20. if (home) {
  21. // homedir() returns undefined if $HOME not set; path.resolve requires strings
  22. var userConfig = path.resolve(home, '.npmrc');
  23. prefix = tryConfigPath(userConfig);
  24. }
  25. if (!prefix) {
  26. // Otherwise find the path of npm
  27. var npm = tryNpmPath();
  28. if (npm) {
  29. // Check the built-in npm config file
  30. var builtinConfig = path.resolve(npm, '..', '..', 'npmrc');
  31. prefix = tryConfigPath(builtinConfig);
  32. if (prefix) {
  33. // Now the global npm config can also be checked.
  34. var globalConfig = path.resolve(prefix, 'etc', 'npmrc');
  35. prefix = tryConfigPath(globalConfig) || prefix;
  36. }
  37. }
  38. if (!prefix) fallback();
  39. }
  40. }
  41. if (prefix) {
  42. return expand(prefix);
  43. }
  44. }
  45. function fallback() {
  46. var isWindows = require('is-windows');
  47. if (isWindows()) {
  48. // c:\node\node.exe --> prefix=c:\node\
  49. prefix = process.env.APPDATA
  50. ? path.join(process.env.APPDATA, 'npm')
  51. : path.dirname(process.execPath);
  52. } else {
  53. // /usr/local/bin/node --> prefix=/usr/local
  54. prefix = path.dirname(path.dirname(process.execPath));
  55. // destdir only is respected on Unix
  56. if (process.env.DESTDIR) {
  57. prefix = path.join(process.env.DESTDIR, prefix);
  58. }
  59. }
  60. }
  61. function tryNpmPath() {
  62. try {
  63. return fs.realpathSync(require('which').sync('npm'));
  64. } catch (err) {}
  65. return null;
  66. }
  67. function tryConfigPath(configPath) {
  68. try {
  69. var data = fs.readFileSync(configPath, 'utf-8');
  70. var config = ini.parse(data);
  71. if (config.prefix) return config.prefix;
  72. } catch (err) {}
  73. return null;
  74. }
  75. /**
  76. * Expose `prefix`
  77. */
  78. Object.defineProperty(module, 'exports', {
  79. enumerable: true,
  80. get: function() {
  81. return prefix || (prefix = getPrefix());
  82. }
  83. });