下記のディレクトリ構造から、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' }
]