Last active
November 16, 2020 15:49
-
-
Save maxichrome/b09dfcbe83b655c312d2ed48fde6a9d0 to your computer and use it in GitHub Desktop.
Recursively, synchronously read a directory in Node.js
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
| /* | |
| Output will be formatted like | |
| [ 'file', 'directory/file.ts', 'directory/subdir/otherfile.ts', 'directory/subdir/file.txt' ] | |
| */ | |
| function readdirSyncRecurse (directory) { | |
| const output = [] | |
| const items = fs.readdirSync(directory) | |
| for (const item of items) { | |
| const itemPath = path.resolve(directory, item) | |
| const stat = fs.statSync(itemPath) | |
| if (stat && stat.isDirectory()) { | |
| const subItems = readdirSyncRecurse(itemPath) | |
| for (const subItem of subItems) { | |
| output.push(path.join(item, subItem)) | |
| } | |
| } else { | |
| output.push(item) | |
| } | |
| } | |
| return output | |
| } |
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
| /* | |
| *** TYPESCRIPT VERSION *** | |
| Output will be formatted like | |
| [ 'file', 'directory/file.ts', 'directory/subdir/otherfile.ts', 'directory/subdir/file.txt' ] | |
| */ | |
| export function readdirSyncRecurse (directory: string): string[] { | |
| const output: string[] = [] | |
| const items = fs.readdirSync(directory) | |
| for (const item of items) { | |
| const itemPath = path.resolve(directory, item) | |
| const stat = fs.statSync(itemPath) | |
| if (stat?.isDirectory()) { | |
| const subItems = readdirSyncRecurse(itemPath) | |
| for (const subItem of subItems) { | |
| output.push(path.join(item, subItem)) | |
| } | |
| } else { | |
| output.push(item) | |
| } | |
| } | |
| return output | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment