Skip to content

Instantly share code, notes, and snippets.

@Makio64
Last active May 28, 2022 02:37
Show Gist options
  • Save Makio64/d4e0d498f079bc829b496d6c642de331 to your computer and use it in GitHub Desktop.
Save Makio64/d4e0d498f079bc829b496d6c642de331 to your computer and use it in GitHub Desktop.
Node get all files until a certain directory depth
const path = require('path')
const fs = require('fs')
// adapted from https://techbrij.com/nodejs-traverse-directory-recursively-depth
function getFilesDepth (dirPath, maxDepth, currentDepth = 0, files = []) {
if (currentDepth <= maxDepth) {
fs.readdirSync(dirPath).forEach(function (file) {
const filepath = path.join(dirPath, file)
const stat = fs.statSync(filepath)
if (stat.isDirectory()) {
getFilesDepth(filepath, maxDepth, currentDepth + 1, files)
} else {
files.push(filepath)
}
})
}
return files
}
console.log(getFilesDepth('yourFolderToLookInto/', 2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment