LoginSignup
21
14

More than 5 years have passed since last update.

特定ディレクトリ配下のファイルのみ(またはディレクトリのみ)を取得(Node.js v10.10以降版)

Posted at

Node.js で特定ディレクトリ配下のファイルのみ(またはディレクトリのみ)を取得するには、以前は特定ディレクトリ配下のリストを取得して、1つずつ fs.stat でファイルか否か判定する必要がありました。
しかし、Node.js v10.10.0 で新たに追加されたオプションによってちょっとだけ簡単に書けるようになりました。

TL;DR

fs.readdir または fs.readdirSync のオプションで withFileTypes: true を指定する。


以下のサンプルは、特定ディレクトリ配下のファイルのみを取得するコードですが、ディレクトリのみを取得する場合も同様で stat.isDirectory()dirent.isDirectory() とするだけです。
また、コードの読みやすさのために同期版API( fs.readdirSync など)を使用していますが、非同期版APIでも同じです。

Node.js v10.10 より前の書き方

node.js
const fs = require("fs");

const isFile = path => {
  const stat = fs.statSync(path);
  return stat.isFile();
}

const dirPath = "path/to/target";

// "path/to/target" 直下のファイルやディレクトリ名全てが文字列の配列で返ってくる
const allNames = fs.readdirSync(dirPath);

const fileNames = allNames.filter(name => isFile(`${dirPath}/${name}`))  

Node.js v10.10 以降でのちょっと簡単な書き方

node.js
const fs = require("fs");

const dirPath = "path/to/target";

// "path/to/target" 直下のファイルやディレクトリ全てがDirentオブジェクトの配列で返ってくる
const allDirents = fs.readdirSync(dirPath, { withFileTypes: true });

const fileNames = allDirents.filter(dirent => dirent.isFile()).map(({ name }) => name);
  • withFileTypes のデフォルト値は false のため、何も指定しない場合は従来と同じ挙動となります。
  • withFileTypes: true を指定すると、戻り値の型がDirentオブジェクトの配列に変わります。

参考

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