4
2

More than 3 years have passed since last update.

Node.jsでディレクトリ配下にあるファイルを再帰的に探索する

Posted at

下記のディレクトリ構造から、txtファイルのpathとfile名を一覧で取得する方法(Node.js)です。

./dir
├── dir2
│   ├── dir3
│   │   ├── file2.txt
│   │   └── file3.md
│   ├── file2.txt
│   └── file3.md
├── file1.md
└── file1.txt

実装コード

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

const searchFiles = (dirPath) => {
  const allDirents = fs.readdirSync(dirPath, { withFileTypes: true });

  const files = [];
  for (const dirent of allDirents) {
    if (dirent.isDirectory()) {
      const fp = path.join(dirPath, dirent.name);
      files.push(searchFiles(fp));
    } else if (dirent.isFile() && ['.txt'].includes(path.extname(dirent.name))) {
      files.push({
        dir: path.join(dirPath, dirent.name),
        name: dirent.name,
      });
    }
  }
  return files.flat();
};

const dirPath = './dir';
console.log(searchFiles(dirPath));

出力内容

[
  { dir: 'dir/dir2/dir3/file2.txt', name: 'file2.txt' },
  { dir: 'dir/dir2/file2.txt', name: 'file2.txt' },
  { dir: 'dir/file1.txt', name: 'file1.txt' }
]
4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2