resolveFilePath.mjs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import { join, normalize, resolve, sep } from 'node:path';
  2. import { lstatSync } from 'node:fs';
  3. /**
  4. * Return the resolved file path, based on whether the provided parameter is
  5. * a directory or looks like a directory (ends in `path.sep`), in which case the file
  6. * name will be `location/defaultFileName`.
  7. *
  8. * If location points to a file or looks like a file, then it will just use that file.
  9. *
  10. * @param {string} location - The name of file or directory to be used
  11. * @param {string} cwd - Current working directory. Used for tests
  12. * @param {string} defaultFileName - Default filename to use when location is a directory
  13. * @returns {string} Resolved path to the file
  14. */
  15. export default function resolveFilePath(location, cwd, defaultFileName) {
  16. /*
  17. * Make sure path separators are normalized for environment/os.
  18. * Also, keep trailing path separator if present.
  19. */
  20. const normalizedLocation = normalize(location);
  21. const resolvedLocation = resolve(cwd, normalizedLocation);
  22. // If the location path ends with a separator, we assume is a directory.
  23. const looksLikeADirectory = location.endsWith(sep);
  24. if (
  25. looksLikeADirectory ||
  26. lstatSync(resolvedLocation, { throwIfNoEntry: false })?.isDirectory()
  27. ) {
  28. // Return path to provided directory with the specified file name.
  29. return join(resolvedLocation, defaultFileName);
  30. }
  31. // Return normalized path to file.
  32. return resolvedLocation;
  33. }