Last active
May 5, 2020 04:20
-
-
Save moranbw/72913690b45c6717adbfee6e78485d47 to your computer and use it in GitHub Desktop.
Recursively get a list of files from a directory using async / await
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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