あるディレクトリ配下に存在する全てのファイルに対しアクションを行いたい場合、klawやklaw-syncが便利だと知ったのでメモ。
元々は、fs
の拡張であるfs-extra
の内に含まれていたwalk
が同じ役割を果たしていたようだが、
What happened to
walk()
andwalkSync()
?
They were removed fromfs-extra
in v2.0.0. If you need the functionality,walk
and walkSync are available as separate packages,klaw
andklaw-sync
.
とのことで、現在は個別にインストールする必要がある。
const klawSync = require('klaw-sync');
let filelist = [];
try {
filelist = klawSync('/foo/bar', {
nodir: true // nodirを有効にすることでファイル名のみを出力
});
} catch (err) {
console.error(err);
}
dirent
の形式でファイルリストが出力される。
[
{
path: '/foo/bar/xxx.js',
stats: Stats {
dev: 16777221,
mode: 33188,
nlink: 1,
uid: 502,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 725582,
size: 5523,
blocks: 16,
atimeMs: 1589185938547.9219,
mtimeMs: 1589185934632.984,
ctimeMs: 1589185934632.984,
birthtimeMs: 1589185934632.7583,
atime: 2020-05-11T08:32:18.548Z,
mtime: 2020-05-11T08:32:14.633Z,
ctime: 2020-05-11T08:32:14.633Z,
birthtime: 2020-05-11T08:32:14.633Z
}
}
]
今までfs.readDir
とfs.stat
を用いて膨大な処理を書いていたのでお手軽さに驚き。積極的に使っていきたい。