Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

path-utils.js 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /**
  2. * @fileoverview Common helpers for operations on filenames and paths
  3. * @author Ian VanSchooten
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const path = require("path");
  10. //------------------------------------------------------------------------------
  11. // Private
  12. //------------------------------------------------------------------------------
  13. /**
  14. * Replace Windows with posix style paths
  15. *
  16. * @param {string} filepath Path to convert
  17. * @returns {string} Converted filepath
  18. */
  19. function convertPathToPosix(filepath) {
  20. const normalizedFilepath = path.normalize(filepath);
  21. const posixFilepath = normalizedFilepath.replace(/\\/g, "/");
  22. return posixFilepath;
  23. }
  24. /**
  25. * Converts an absolute filepath to a relative path from a given base path
  26. *
  27. * For example, if the filepath is `/my/awesome/project/foo.bar`,
  28. * and the base directory is `/my/awesome/project/`,
  29. * then this function should return `foo.bar`.
  30. *
  31. * path.relative() does something similar, but it requires a baseDir (`from` argument).
  32. * This function makes it optional and just removes a leading slash if the baseDir is not given.
  33. *
  34. * It does not take into account symlinks (for now).
  35. *
  36. * @param {string} filepath Path to convert to relative path. If already relative,
  37. * it will be assumed to be relative to process.cwd(),
  38. * converted to absolute, and then processed.
  39. * @param {string} [baseDir] Absolute base directory to resolve the filepath from.
  40. * If not provided, all this function will do is remove
  41. * a leading slash.
  42. * @returns {string} Relative filepath
  43. */
  44. function getRelativePath(filepath, baseDir) {
  45. const absolutePath = path.isAbsolute(filepath)
  46. ? filepath
  47. : path.resolve(filepath);
  48. if (baseDir) {
  49. if (!path.isAbsolute(baseDir)) {
  50. throw new Error(`baseDir should be an absolute path: ${baseDir}`);
  51. }
  52. return path.relative(baseDir, absolutePath);
  53. }
  54. return absolutePath.replace(/^\//, "");
  55. }
  56. //------------------------------------------------------------------------------
  57. // Public Interface
  58. //------------------------------------------------------------------------------
  59. module.exports = {
  60. convertPathToPosix,
  61. getRelativePath
  62. };