获取所有子目录并返回它们的路径?

huangapple go评论96阅读模式
英文:

How to get all subdirectories and return their paths?

问题

[
'apps/group1/project1',
'apps/group1/project2',
'apps/group2/project3',
'apps/group2/project4'
]

英文:

Assume there is the following folder structure:

  1. /apps
  2. |- /group1
  3. | |- /project1
  4. | |- /project2
  5. |- /group2
  6. | |- /project3
  7. | |- /project4

I need to get the path of all projects - which are all two level deep (group folder and then project folder).

So I started with this:

  1. import { readdirSync } from 'fs'
  2. const directoriesInDirectory = readdirSync([rootPath, 'apps'].join('/'), {
  3. withFileTypes: true
  4. })
  5. .filter((item) => item.isDirectory())
  6. .map((item) => item.name)

This gives me all groups ['group1', 'group2'].

But I need to get this:

  1. [
  2. 'apps/group1/project1',
  3. 'apps/group1/project2',
  4. 'apps/group2/project3',
  5. 'apps/group2/project4'
  6. ]

答案1

得分: 0

你需要多次执行readdirSync,一次用于app目录,其余用于嵌套目录。另外,可以使用 promises 来替代同步操作,如下所示:

  1. import { readdir } from 'fs/promises';
  2. const startPath = [rootPath, 'apps'].join('/');
  3. const parentDirs = (
  4. await readdir(startPath, {
  5. withFileTypes: true,
  6. })
  7. )
  8. .filter((item) => item.isDirectory())
  9. .map((item) => item.name);
  10. const projectPaths = (
  11. await Promise.all(
  12. parentDirs.map(async (dir) => {
  13. const projects = (
  14. await readdir(startPath + '/' + dir, {
  15. withFileTypes: true,
  16. })
  17. )
  18. .filter((item) => item.isDirectory())
  19. .map((item) => item.name);
  20. return { dir, projects };
  21. })
  22. )
  23. )
  24. .map(({ dir, projects }) =>
  25. projects.map((project) => [startPath, dir, project].join('/'))
  26. )
  27. .flat();
  28. console.log(projectPaths); // ['apps/group1/project1', 'apps/group1/project2', ...]
英文:

You need to perform readdirSync multiple times, once for the app directory, and the rest for the nested directories. Also, instead of using sync, if you adapt the non-blocking nature, you can use promises instead:

  1. import { readdir } from 'fs/promises'
  2. const startPath = [rootPath, 'apps'].join('/')
  3. const parentDirs = (
  4. await readdir(startPath, {
  5. withFileTypes: true,
  6. })
  7. )
  8. .filter((item) => item.isDirectory())
  9. .map((item) => item.name)
  10. const projectPaths = (
  11. await Promise.all(
  12. parentDirs.map(async (dir) => {
  13. const projects = (
  14. await readdir(startPath + '/' + dir, {
  15. withFileTypes: true,
  16. })
  17. )
  18. .filter((item) => item.isDirectory())
  19. .map((item) => item.name)
  20. return { dir, projects }
  21. })
  22. )
  23. )
  24. .map(({ dir, projects }) =>
  25. projects.map((project) => [startPath, dir, projects].join('/'))
  26. )
  27. .flat()
  28. console.log(projectPaths) // ['apps/group1/project1', 'apps/group1/project2', ...]

答案2

得分: 0

我相信这段代码应该能够满足您的需求,如果您添加更多子目录,不确定它是否能够正常工作,我进行了有限的测试,但应该可以正常运行。

  1. const fs = require("fs");
  2. const path = require("path");
  3. function getSubdirectories(rootPath) {
  4. const result = [];
  5. const directoriesInDirectory = fs
  6. .readdirSync(rootPath, {
  7. withFileTypes: true
  8. })
  9. .filter(item => item.isDirectory())
  10. .map(item => item.name);
  11. directoriesInDirectory.forEach(dir => {
  12. const subdirectories = getSubdirectories(path.join(rootPath, dir));
  13. // 对于根目录中的每个目录,检查是否有子目录
  14. if (subdirectories.length > 0) {
  15. subdirectories.forEach(subdir => {
  16. result.push(path.join(dir, subdir));
  17. });
  18. } else {
  19. result.push(dir);
  20. }
  21. });
  22. return result;
  23. }
  24. const subdirectories = getSubdirectories("./app");
  25. const subdirectoryPaths = subdirectories.map(subdir => {
  26. return path.join("app", subdir);
  27. });
  28. console.log(subdirectoryPaths);

希望这对您有帮助。

英文:

I believe this code should do what you need, I dont know how well it would work if you add more subdirectories, I did limited testing, but it should work fine.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

  1. const fs = require(&quot;fs&quot;);
  2. const path = require(&quot;path&quot;);
  3. function getSubdirectories(rootPath) {
  4. const result = [];
  5. const directoriesInDirectory = fs
  6. .readdirSync(rootPath, {
  7. withFileTypes: true
  8. })
  9. .filter(item =&gt; item.isDirectory())
  10. .map(item =&gt; item.name);
  11. directoriesInDirectory.forEach(dir =&gt; {
  12. const subdirectories = getSubdirectories(path.join(rootPath, dir));
  13. // for each directory in the root directory, check if it has subdirectories
  14. if (subdirectories.length &gt; 0) {
  15. subdirectories.forEach(subdir =&gt; {
  16. result.push(path.join(dir, subdir));
  17. });
  18. } else {
  19. result.push(dir);
  20. }
  21. });
  22. return result;
  23. }
  24. const subdirectories = getSubdirectories(&quot;./app&quot;);
  25. const subdirectoryPaths = subdirectories.map(subdir =&gt; {
  26. return path.join(&quot;app&quot;, subdir);
  27. });
  28. console.log(subdirectoryPaths);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月19日 06:05:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75496679.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定