index.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. 'use strict';
  2. const path = require('path');
  3. const os = require('os');
  4. const fs = require('fs');
  5. const ini = require('ini');
  6. const readRc = fp => {
  7. try {
  8. return ini.parse(fs.readFileSync(fp, 'utf8')).prefix;
  9. } catch (err) {}
  10. };
  11. const defaultNpmPrefix = (() => {
  12. if (process.env.PREFIX) {
  13. return process.env.PREFIX;
  14. }
  15. if (process.platform === 'win32') {
  16. // `c:\node\node.exe` → `prefix=c:\node\`
  17. return path.dirname(process.execPath);
  18. }
  19. // `/usr/local/bin/node` → `prefix=/usr/local`
  20. return path.dirname(path.dirname(process.execPath));
  21. })();
  22. const getNpmPrefix = () => {
  23. if (process.env.PREFIX) {
  24. return process.env.PREFIX;
  25. }
  26. const homePrefix = readRc(path.join(os.homedir(), '.npmrc'));
  27. if (homePrefix) {
  28. return homePrefix;
  29. }
  30. const globalConfigPrefix = readRc(path.resolve(defaultNpmPrefix, 'etc', 'npmrc'));
  31. if (globalConfigPrefix) {
  32. return globalConfigPrefix;
  33. }
  34. if (process.platform === 'win32' && process.env.APPDATA) {
  35. // Hardcoded contents of `c:\Program Files\nodejs\node_modules\npm\.npmrc`
  36. const prefix = path.join(process.env.APPDATA, 'npm');
  37. if (fs.existsSync(prefix)) {
  38. return prefix;
  39. }
  40. }
  41. return defaultNpmPrefix;
  42. };
  43. const npmPrefix = path.resolve(getNpmPrefix());
  44. const getYarnPrefix = () => {
  45. if (process.env.PREFIX) {
  46. return process.env.PREFIX;
  47. }
  48. if (process.platform === 'win32' && process.env.LOCALAPPDATA) {
  49. const prefix = path.join(process.env.LOCALAPPDATA, 'Yarn');
  50. if (fs.existsSync(prefix)) {
  51. return prefix;
  52. }
  53. }
  54. const configPrefix = path.join(os.homedir(), '.config/yarn');
  55. if (fs.existsSync(configPrefix)) {
  56. return configPrefix;
  57. }
  58. const homePrefix = path.join(os.homedir(), '.yarn-config');
  59. if (fs.existsSync(homePrefix)) {
  60. return homePrefix;
  61. }
  62. // Yarn supports the npm conventions but the inverse is not true
  63. return npmPrefix;
  64. };
  65. exports.npm = {};
  66. exports.npm.prefix = npmPrefix;
  67. exports.npm.packages = path.join(npmPrefix, process.platform === 'win32' ? 'node_modules' : 'lib/node_modules');
  68. exports.npm.binaries = process.platform === 'win32' ? npmPrefix : path.join(npmPrefix, 'bin');
  69. const yarnPrefix = path.resolve(getYarnPrefix());
  70. exports.yarn = {};
  71. exports.yarn.prefix = yarnPrefix;
  72. exports.yarn.packages = path.join(yarnPrefix, process.platform === 'win32' ? 'config/global/node_modules' : 'global/node_modules');
  73. exports.yarn.binaries = path.join(exports.yarn.packages, '.bin');