Get all files in a folder recursively using Node JS using Generators
This function will help us to get all the files inside a folder, even if the folder has folders inside.
This function is using function*
and yield
, you can find more information related to generators and yield.
This function does:
- Read all the files of the first level of the folder.
- Then iterate over all the files inside, including files and folder.
- Under the iteration, it validates if the node is a folder o a file.
- If is a folder, we recursively call this same function, under the actual
dir
. - If is not a folder, we attach the result to the yield result.
const fs = require('fs');
const path = require('path');
// Definition
function *matchSync(dir) {
const files = fs.readdirSync(dir, { withFileTypes: true });
for (let i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
yield* matchSync(path.join(dir, files[i].name));
} else {
yield path.join(dir, files[i].name);
}
}
}
// Usage
for (let i of matchSync(__dirname)) {
console.log(i);
}
Happy Coding!