TAKEO

TAKEO

Node.jsでディレクトリ下のファイルを列挙する

Node.jsでディレクトリ下のファイルへのパスを再帰的に列挙する方法について紹介します。例えば次のようなディレクトリがあった時に、各ファイルへのパスを取得したい時に使います。

Copied!!
$ tree test
test
├── test1
│   └── test.js
├── test2
│   └── test2.js
├── test3
│   ├── test3.md
│   └── test4
│       └── test4.md
└── test.md

4 directories, 5 files

TL;DR

test.js
Copied!!
const fs = require("fs");
const path = require("path");
// ディレクトリ名は任意に指定してください
const dirents = fs.readdirSync("./test", {
  withFileTypes: true,
  recursive: true,
});

for (dirent of dirents) {
  if (dirent.isFile()) {
    console.log(dirent);
    // filePath = path.join(dirent.path, dirent.name);
    // console.log(filePath);
  }
}
出力例
Copied!!
$ node test.js
Dirent { name: 'test.md', path: './test', [Symbol(type)]: 1 }
Dirent { name: 'test.js', path: 'test/test1', [Symbol(type)]: 1 }
Dirent { name: 'test2.js', path: 'test/test2', [Symbol(type)]: 1 }
Dirent { name: 'test3.md', path: 'test/test3', [Symbol(type)]: 1 }
Dirent {
  name: 'test4.md',
  path: 'test/test3/test4',
  [Symbol(type)]: 1
}
  • 出力しているものはdirentオブジェクトなので、パスにしたい時は次のように変更してください

    変更点(diff形式)
    Copied!!
    for (dirent of dirents) {
      if (dirent.isFile()) {
    -   console.log(dirent);
    +   filePath = path.join(dirent.path, dirent.name);
    +   console.log(filePath);
      }
    }