index.js 2.0 KB

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