[go: up one dir, main page]

Skip to content

Instantly share code, notes, and snippets.

@moranbw
Last active May 5, 2020 04:20
Show Gist options
  • Save moranbw/72913690b45c6717adbfee6e78485d47 to your computer and use it in GitHub Desktop.
Save moranbw/72913690b45c6717adbfee6e78485d47 to your computer and use it in GitHub Desktop.
Recursively get a list of files from a directory using async / await
const fs = require('fs');
const path = "/your/data/path";
(async () => {
async function recurseDir(aDir, aArr, aCond) {
//remove trailing slash if it's there
aDir = aDir.replace("\/+$", "");
let dirents = await fs.promises.readdir(aDir, { withFileTypes: true });
for (const aDirent of dirents) {
if (aDirent.isDirectory()) {
await recurseDir(aDir + "/" + aDirent.name, aArr, aCond);
} else {
//optionally check for an extension
if (aDirent.name.endsWith(aCond)) {
aArr.push(aDir + "/" + aDirent.name);
}
}
}
return aArr;
};
let files = await recurseDir(path, [], "");
console.log(files.length);
//write list of files to a file
let outputFile = fs.createWriteStream('files.txt');
outputFile.on('error', function (aErr) {
console.log("Couldn't create file")
});
for (const aFile of files) {
outputFile.write(aFile + '\n');
}
outputFile.end();
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment