path.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. "use strict";
  2. function isDirectoryIndex(resource, options)
  3. {
  4. var verdict = false;
  5. options.directoryIndexes.every( function(index)
  6. {
  7. if (index === resource)
  8. {
  9. verdict = true;
  10. return false;
  11. }
  12. return true;
  13. });
  14. return verdict;
  15. }
  16. function parsePath(urlObj, options)
  17. {
  18. var path = urlObj.path.absolute.string;
  19. if (path)
  20. {
  21. var lastSlash = path.lastIndexOf("/");
  22. if (lastSlash > -1)
  23. {
  24. if (++lastSlash < path.length)
  25. {
  26. var resource = path.substr(lastSlash);
  27. if (resource!=="." && resource!=="..")
  28. {
  29. urlObj.resource = resource;
  30. path = path.substr(0, lastSlash);
  31. }
  32. else
  33. {
  34. path += "/";
  35. }
  36. }
  37. urlObj.path.absolute.string = path;
  38. urlObj.path.absolute.array = splitPath(path);
  39. }
  40. else if (path==="." || path==="..")
  41. {
  42. // "..?var", "..#anchor", etc ... not "..index.html"
  43. path += "/";
  44. urlObj.path.absolute.string = path;
  45. urlObj.path.absolute.array = splitPath(path);
  46. }
  47. else
  48. {
  49. // Resource-only
  50. urlObj.resource = path;
  51. urlObj.path.absolute.string = null;
  52. }
  53. urlObj.extra.resourceIsIndex = isDirectoryIndex(urlObj.resource, options);
  54. }
  55. // Else: query/hash-only or empty
  56. }
  57. function splitPath(path)
  58. {
  59. // TWEAK :: condition only for speed optimization
  60. if (path !== "/")
  61. {
  62. var cleaned = [];
  63. path.split("/").forEach( function(dir)
  64. {
  65. // Cleanup -- splitting "/dir/" becomes ["","dir",""]
  66. if (dir !== "")
  67. {
  68. cleaned.push(dir);
  69. }
  70. });
  71. return cleaned;
  72. }
  73. else
  74. {
  75. // Faster to skip the above block and just create an array
  76. return [];
  77. }
  78. }
  79. module.exports = parsePath;