tree-dir.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import fsp from 'fs/promises';
  2. import { sep } from 'path';
  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 tree: TreeTypeArray = [];
  19. const walk = async (dir: string, node: TreeTypeArray): Promise<VoidOrVoidArray> => {
  20. const promises: Array<Promise<VoidOrVoidArray>> = [];
  21. for await (const child of await fsp.opendir(dir)) {
  22. const childFullPath = child.parentPath + sep + child.name;
  23. if (child.isDirectory()) {
  24. const newNode: TreeDirectoryType = {
  25. type: 'directory',
  26. name: child.name,
  27. path: childFullPath,
  28. children: []
  29. };
  30. node.push(newNode);
  31. promises.push(walk(childFullPath, newNode.children));
  32. continue;
  33. }
  34. if (child.isFile()) {
  35. const newNode: TreeFileType = {
  36. type: 'file',
  37. name: child.name,
  38. path: childFullPath
  39. };
  40. node.push(newNode);
  41. continue;
  42. }
  43. }
  44. return Promise.all(promises);
  45. };
  46. await walk(path, tree);
  47. return tree;
  48. };