Last active
February 26, 2021 21:22
-
-
Save senthilmpro/1789b8299afbfabf807da634c9875cad to your computer and use it in GitHub Desktop.
Get all files in a directory recursively - Node.js
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'); | |
// SOURCE: https://dev.to/leonard/get-files-recursive-with-the-node-js-file-system-fs-2n7o | |
const FileService = { | |
getAllFiles: async (path = "./") => { | |
const entries = await fs.readdirSync(path, { | |
withFileTypes: true | |
}); | |
// Get files within the current directory and add a path key to the file objects | |
const files = entries | |
.filter(file => !file.isDirectory()) | |
.map(file => ({ | |
...file, | |
path: path + file.name | |
})); | |
// Get folders within the current directory | |
const folders = entries.filter(folder => folder.isDirectory()); | |
for (const folder of folders) | |
/* | |
Add the found files within the subdirectory to the files array by calling the | |
current function itself | |
*/ | |
files.push(...await FileService.getAllFiles(`${path}${folder.name}/`)); | |
return files; | |
} | |
} | |
module.exports = FileService; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment