31 August 2019 0 comments JavaScript
It started with this:
function walk(directory, filepaths = []) {
const files = fs.readdirSync(directory);
for (let filename of files) {
const filepath = path.join(directory, filename);
if (fs.statSync(filepath).isDirectory()) {
walk(filepath, filepaths);
} else if (path.extname(filename) === '.md') {
filepaths.push(filepath);
}
}
return filepaths;
}
And you use it like this:
const foundFiles = walk(someDirectoryOfMine);
console.log(foundFiles.length);
I thought, perhaps it's faster or better to use glob
. So I installed that.
Then I found, fast-glob
which sounds faster. You use both in a synchronous way.
I have a directory with about 450 files, of which 320 of them are .md
files. Let's compare:
walk: 10.212ms glob: 37.492ms fg: 14.200ms
I measured it using
console.time
like this:
console.time('walk');
const foundFiles = walk(someDirectoryOfMine);
console.timeEnd('walk');
console.log(foundFiles.length);
I suppose those packages have other fancier features but, I guess this just goes to show, keep it simple.