tree-dir.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import type { Path } from 'path-scurry';
  2. import { PathScurry } from 'path-scurry';
  3. interface TreeFileType {
  4. type: 'file',
  5. name: string,
  6. path: string
  7. }
  8. interface TreeDirectoryType {
  9. type: 'directory',
  10. name: string,
  11. path: string,
  12. children: TreeTypeArray
  13. }
  14. export type TreeType = TreeDirectoryType | TreeFileType;
  15. export type TreeTypeArray = TreeType[];
  16. type VoidOrVoidArray = void | VoidOrVoidArray[];
  17. export const treeDir = async (path: string): Promise<TreeTypeArray> => {
  18. const pw = new PathScurry(path);
  19. const tree: TreeTypeArray = [];
  20. const walk = async (entry: Path, node: TreeTypeArray): Promise<VoidOrVoidArray> => {
  21. const promises: Array<Promise<VoidOrVoidArray>> = [];
  22. for (const child of await pw.readdir(entry)) {
  23. if (child.isDirectory()) {
  24. const newNode: TreeDirectoryType = {
  25. type: 'directory',
  26. name: child.name,
  27. path: child.relative(),
  28. children: []
  29. };
  30. node.push(newNode);
  31. promises.push(walk(child, newNode.children));
  32. continue;
  33. }
  34. if (child.isFile()) {
  35. const newNode: TreeFileType = {
  36. type: 'file',
  37. name: child.name,
  38. path: child.relative()
  39. };
  40. node.push(newNode);
  41. continue;
  42. }
  43. }
  44. return Promise.all(promises);
  45. };
  46. await walk(pw.cwd, tree);
  47. return tree;
  48. };