utils.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import * as fs from 'fs';
  2. import * as path from 'path';
  3. /**
  4. * Recursively read the contents of a directory.
  5. *
  6. * @param targetDir Absolute or relative path of the directory to scan. All returned paths will be relative to this
  7. * directory.
  8. * @returns Array holding all relative paths
  9. * @deprecated This function will be removed in the next major version.
  10. */
  11. function deepReadDirSync(targetDir) {
  12. const targetDirAbsPath = path.resolve(targetDir);
  13. if (!fs.existsSync(targetDirAbsPath)) {
  14. throw new Error(`Cannot read contents of ${targetDirAbsPath}. Directory does not exist.`);
  15. }
  16. if (!fs.statSync(targetDirAbsPath).isDirectory()) {
  17. throw new Error(`Cannot read contents of ${targetDirAbsPath}, because it is not a directory.`);
  18. }
  19. // This does the same thing as its containing function, `deepReadDirSync` (except that - purely for convenience - it
  20. // deals in absolute paths rather than relative ones). We need this to be separate from the outer function to preserve
  21. // the difference between `targetDirAbsPath` and `currentDirAbsPath`.
  22. const deepReadCurrentDir = (currentDirAbsPath) => {
  23. return fs.readdirSync(currentDirAbsPath).reduce((absPaths, itemName) => {
  24. const itemAbsPath = path.join(currentDirAbsPath, itemName);
  25. if (fs.statSync(itemAbsPath).isDirectory()) {
  26. return absPaths.concat(deepReadCurrentDir(itemAbsPath));
  27. }
  28. absPaths.push(itemAbsPath);
  29. return absPaths;
  30. }, []);
  31. };
  32. return deepReadCurrentDir(targetDirAbsPath).map(absPath => path.relative(targetDirAbsPath, absPath));
  33. }
  34. export { deepReadDirSync };
  35. //# sourceMappingURL=utils.js.map