index.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. 'use strict';
  2. var path = require('path');
  3. var isAbsolute = require('is-absolute');
  4. var pathRoot = require('path-root');
  5. var MapCache = require('map-cache');
  6. var cache = new MapCache();
  7. module.exports = function(filepath) {
  8. if (typeof filepath !== 'string') {
  9. throw new TypeError('parse-filepath expects a string');
  10. }
  11. if (cache.has(filepath)) {
  12. return cache.get(filepath);
  13. }
  14. var obj = {};
  15. if (typeof path.parse === 'function') {
  16. obj = path.parse(filepath);
  17. obj.extname = obj.ext;
  18. obj.basename = obj.base;
  19. obj.dirname = obj.dir;
  20. obj.stem = obj.name;
  21. } else {
  22. define(obj, 'root', function() {
  23. return pathRoot(this.path);
  24. });
  25. define(obj, 'extname', function() {
  26. return path.extname(filepath);
  27. });
  28. define(obj, 'ext', function() {
  29. return this.extname;
  30. });
  31. define(obj, 'name', function() {
  32. return path.basename(filepath, this.ext);
  33. });
  34. define(obj, 'stem', function() {
  35. return this.name;
  36. });
  37. define(obj, 'base', function() {
  38. return this.name + this.ext;
  39. });
  40. define(obj, 'basename', function() {
  41. return this.base;
  42. });
  43. define(obj, 'dir', function() {
  44. return path.dirname(filepath);
  45. });
  46. define(obj, 'dirname', function() {
  47. return this.dir;
  48. });
  49. }
  50. obj.path = filepath;
  51. define(obj, 'absolute', function() {
  52. return path.resolve(this.path);
  53. });
  54. define(obj, 'isAbsolute', function() {
  55. return isAbsolute(this.path);
  56. });
  57. cache.set(filepath, obj);
  58. return obj;
  59. };
  60. function define(obj, prop, fn) {
  61. var cached;
  62. Object.defineProperty(obj, prop, {
  63. configurable: true,
  64. enumerable: true,
  65. set: function(val) {
  66. cached = val;
  67. },
  68. get: function() {
  69. return cached || (cached = fn.call(obj));
  70. }
  71. });
  72. }