index.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. 'use strict';
  2. var isWindows = process.platform === 'win32';
  3. // Regex to split a windows path into into [dir, root, basename, name, ext]
  4. var splitWindowsRe =
  5. /^(((?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?[\\\/]?)(?:[^\\\/]*[\\\/])*)((\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))[\\\/]*$/;
  6. var win32 = {};
  7. function win32SplitPath(filename) {
  8. return splitWindowsRe.exec(filename).slice(1);
  9. }
  10. win32.parse = function(pathString) {
  11. if (typeof pathString !== 'string') {
  12. throw new TypeError(
  13. "Parameter 'pathString' must be a string, not " + typeof pathString
  14. );
  15. }
  16. var allParts = win32SplitPath(pathString);
  17. if (!allParts || allParts.length !== 5) {
  18. throw new TypeError("Invalid path '" + pathString + "'");
  19. }
  20. return {
  21. root: allParts[1],
  22. dir: allParts[0] === allParts[1] ? allParts[0] : allParts[0].slice(0, -1),
  23. base: allParts[2],
  24. ext: allParts[4],
  25. name: allParts[3]
  26. };
  27. };
  28. // Split a filename into [dir, root, basename, name, ext], unix version
  29. // 'root' is just a slash, or nothing.
  30. var splitPathRe =
  31. /^((\/?)(?:[^\/]*\/)*)((\.{1,2}|[^\/]+?|)(\.[^.\/]*|))[\/]*$/;
  32. var posix = {};
  33. function posixSplitPath(filename) {
  34. return splitPathRe.exec(filename).slice(1);
  35. }
  36. posix.parse = function(pathString) {
  37. if (typeof pathString !== 'string') {
  38. throw new TypeError(
  39. "Parameter 'pathString' must be a string, not " + typeof pathString
  40. );
  41. }
  42. var allParts = posixSplitPath(pathString);
  43. if (!allParts || allParts.length !== 5) {
  44. throw new TypeError("Invalid path '" + pathString + "'");
  45. }
  46. return {
  47. root: allParts[1],
  48. dir: allParts[0].slice(0, -1),
  49. base: allParts[2],
  50. ext: allParts[4],
  51. name: allParts[3],
  52. };
  53. };
  54. if (isWindows)
  55. module.exports = win32.parse;
  56. else /* posix */
  57. module.exports = posix.parse;
  58. module.exports.posix = posix.parse;
  59. module.exports.win32 = win32.parse;