load-prefix.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. module.exports = loadPrefix
  2. var findPrefix = require('find-npm-prefix')
  3. var path = require('path')
  4. function loadPrefix (cb) {
  5. var cli = this.list[0]
  6. Object.defineProperty(this, 'prefix',
  7. {
  8. set: function (prefix) {
  9. var g = this.get('global')
  10. this[g ? 'globalPrefix' : 'localPrefix'] = prefix
  11. }.bind(this),
  12. get: function () {
  13. var g = this.get('global')
  14. return g ? this.globalPrefix : this.localPrefix
  15. }.bind(this),
  16. enumerable: true
  17. })
  18. Object.defineProperty(this, 'globalPrefix',
  19. {
  20. set: function (prefix) {
  21. this.set('prefix', prefix)
  22. }.bind(this),
  23. get: function () {
  24. return path.resolve(this.get('prefix'))
  25. }.bind(this),
  26. enumerable: true
  27. })
  28. var p
  29. Object.defineProperty(this, 'localPrefix',
  30. { set: function (prefix) { p = prefix },
  31. get: function () { return p },
  32. enumerable: true })
  33. // try to guess at a good node_modules location.
  34. // If we are *explicitly* given a prefix on the cli, then
  35. // always use that. otherwise, infer local prefix from cwd.
  36. if (Object.prototype.hasOwnProperty.call(cli, 'prefix')) {
  37. p = path.resolve(cli.prefix)
  38. process.nextTick(cb)
  39. } else {
  40. findPrefix(process.cwd()).then((found) => {
  41. p = found
  42. cb()
  43. }, cb)
  44. }
  45. }