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

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

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:

/apps
|- /group1
|  |- /project1
|  |- /project2
|- /group2
|  |- /project3
|  |- /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:

import { readdirSync } from 'fs'

const directoriesInDirectory = readdirSync([rootPath, 'apps'].join('/'), {
  withFileTypes: true
})
.filter((item) => item.isDirectory())
.map((item) => item.name)

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

But I need to get this:

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

答案1

得分: 0

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

import { readdir } from 'fs/promises';

const startPath = [rootPath, 'apps'].join('/');

const parentDirs = (
  await readdir(startPath, {
    withFileTypes: true,
  })
)
  .filter((item) => item.isDirectory())
  .map((item) => item.name);

const projectPaths = (
  await Promise.all(
    parentDirs.map(async (dir) => {
      const projects = (
        await readdir(startPath + '/' + dir, {
          withFileTypes: true,
        })
      )
        .filter((item) => item.isDirectory())
        .map((item) => item.name);
      return { dir, projects };
    })
  )
)
  .map(({ dir, projects }) =>
    projects.map((project) => [startPath, dir, project].join('/'))
  )
  .flat();

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:

import { readdir } from 'fs/promises'

const startPath = [rootPath, 'apps'].join('/')

const parentDirs = (
  await readdir(startPath, {
    withFileTypes: true,
  })
)
  .filter((item) => item.isDirectory())
  .map((item) => item.name)

const projectPaths = (
  await Promise.all(
    parentDirs.map(async (dir) => {
      const projects = (
        await readdir(startPath + '/' + dir, {
          withFileTypes: true,
        })
      )
        .filter((item) => item.isDirectory())
        .map((item) => item.name)
      return { dir, projects }
    })
  )
)
  .map(({ dir, projects }) =>
    projects.map((project) => [startPath, dir, projects].join('/'))
  )
  .flat()

console.log(projectPaths) // ['apps/group1/project1', 'apps/group1/project2', ...]

答案2

得分: 0

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

const fs = require("fs");
const path = require("path");

function getSubdirectories(rootPath) {
  const result = [];

  const directoriesInDirectory = fs
    .readdirSync(rootPath, {
      withFileTypes: true
    })
    .filter(item => item.isDirectory())
    .map(item => item.name);

  directoriesInDirectory.forEach(dir => {
    const subdirectories = getSubdirectories(path.join(rootPath, dir));
    // 对于根目录中的每个目录,检查是否有子目录
    if (subdirectories.length > 0) {
      subdirectories.forEach(subdir => {
        result.push(path.join(dir, subdir));
      });
    } else {
      result.push(dir);
    }
  });

  return result;
}

const subdirectories = getSubdirectories("./app");

const subdirectoryPaths = subdirectories.map(subdir => {
  return path.join("app", subdir);
});

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 -->

const fs = require(&quot;fs&quot;);
const path = require(&quot;path&quot;);

function getSubdirectories(rootPath) {
  const result = [];

  const directoriesInDirectory = fs
    .readdirSync(rootPath, {
      withFileTypes: true
    })
    .filter(item =&gt; item.isDirectory())
    .map(item =&gt; item.name);

  directoriesInDirectory.forEach(dir =&gt; {
    const subdirectories = getSubdirectories(path.join(rootPath, dir));
    // for each directory in the root directory, check if it has subdirectories
    if (subdirectories.length &gt; 0) {
      subdirectories.forEach(subdir =&gt; {
        result.push(path.join(dir, subdir));
      });
    } else {
      result.push(dir);
    }
  });

  return result;
}

const subdirectories = getSubdirectories(&quot;./app&quot;);

const subdirectoryPaths = subdirectories.map(subdir =&gt; {
  return path.join(&quot;app&quot;, subdir);
});

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:

确定