Skip to content

Instantly share code, notes, and snippets.

@mvillarrealb
Created March 1, 2019 14:23
Show Gist options
  • Save mvillarrealb/8b6e4268a47c4ac6df28f7514885920c to your computer and use it in GitHub Desktop.
Save mvillarrealb/8b6e4268a47c4ac6df28f7514885920c to your computer and use it in GitHub Desktop.
Scans a directory in a recursive way using promises with async and await
const fs = require('fs');
const path = require('path');
const {
promisify
} = require('util');
/**
Add Promise sugar to the fs.readdir and fs.stat functions
*/
const fsReadDir = promisify(fs.readdir);
const fsStat = promisify(fs.stat);
const recursiveScanAsync = async function (directory) {
const files = await fsReadDir(directory);
const promiseMap = files.map(async file => {
const stat = await fsStat(path.join(directory, file));
let localFiles = [];
if (stat.isDirectory()) {
localFiles = await recursiveScanAsync(path.join(directory, file));
} else {
localFiles.push(path.join(directory, file));
}
return localFiles;
});
/**
* At this point promiseMap is a map of promises containing the recursive scan "promise" we need
to solve all promises using Promise all with await
*/
const finalRes = await Promise.all(promiseMap);
/**
Since generated result is an array of arrays we need to reduce each array
flattening it into a final array using Array.prototype.reduce function
*/
return finalRes.reduce((flat, toFlatten) => {
return flat.concat(toFlatten);
}, []);;
};
(async function () {
const markDownFiles = await recursiveScanAsync('test')
console.log(markDownFiles.filter(file => file.indexOf(".md") >= 0));
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment