Last active
May 28, 2022 02:37
-
-
Save Makio64/d4e0d498f079bc829b496d6c642de331 to your computer and use it in GitHub Desktop.
Node get all files until a certain directory depth
This file contains hidden or 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 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