Last active
January 23, 2025 01:46
-
-
Save bchumney/5a9775967d652a460438719c01891bd2 to your computer and use it in GitHub Desktop.
Walk directory for files in nodejs
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 fs = require('fs'), | |
| path = require('path'), | |
| fs_promise = fs.promises; | |
| async function walk(dir) { | |
| let files = await fs_promise.readdir(dir); | |
| files = await Promise.all(files.map(async file => { | |
| let filePath = path.join(dir, file); | |
| let stats = await fs_promise.stat(filePath); | |
| if (stats.isDirectory()) { | |
| return walk(filePath); | |
| } | |
| else if(stats.isFile()) { | |
| return filePath; | |
| } | |
| })); | |
| return files.reduce((all, folderContents) => all.concat(folderContents), []); | |
| } | |
| //example usage | |
| walk(directory).then(function(files){ | |
| files.sort(); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment