1. /**
  2. * Splits a file path into its components (root, directories, filename).
  3. *
  4. * @param {string} filePath The file path to split.
  5. * @returns {object} An object containing the root, directories, and filename.
  6. * Returns null if the input is not a string.
  7. */
  8. function splitFilePath(filePath) {
  9. if (typeof filePath !== 'string') {
  10. return null; // Handle invalid input
  11. }
  12. const parts = filePath.split(/[\\/]/); // Split by path separators
  13. let root = [];
  14. let directories = [];
  15. let filename = parts.pop(); // Get the last part as the filename
  16. // Reconstruct directories from the remaining parts
  17. for (let i = 0; i < parts.length; i++) {
  18. if (parts[i] !== "") { //avoid empty strings
  19. directories.unshift(parts[i]); // Add directories in the correct order
  20. }
  21. }
  22. return {
  23. root: root.join('\\'), // Join root parts with backslashes
  24. directories: directories.join('\\'), // Join directories with backslashes
  25. filename: filename
  26. };
  27. }

Add your comment