Skip to content

Instantly share code, notes, and snippets.

@hawkeye64
Created November 18, 2018 15:08
Show Gist options
  • Save hawkeye64/b522aa1edd00f738cfa231d047ec3b13 to your computer and use it in GitHub Desktop.
Save hawkeye64/b522aa1edd00f738cfa231d047ec3b13 to your computer and use it in GitHub Desktop.
Generator function that lists all files in a folder recursively in a synchronous fashion
const path = require('path')
const fs = require('fs')
/**
* Generator function that lists all files in a folder recursively
* in a synchronous fashion
*
* @param {String} folder - folder to start with
* @param {Number} recurseLevel - number of times to recurse folders
* @returns {IterableIterator<String>}
*/
function *walkFolders (folder, recurseLevel = 0) {
try {
const files = fs.readdirSync(folder)
for (const file of files) {
try {
const pathToFile = path.join(folder, file)
const stat = fs.statSync(pathToFile)
const isDirectory = stat.isDirectory()
if (isDirectory && recurseLevel > 0) {
yield * walkFolders(pathToFile, recurseLevel - 1)
}
else {
yield {
rootDir: folder,
fileName: file,
isDir: isDirectory,
stat: stat
}
}
}
catch (err) {
yield {
rootDir: folder,
fileName: file,
error: err
}
}
}
}
catch (err) {
yield {
rootDir: folder,
error: err
}
}
}
export default walkFolders
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment