Skip to content

Instantly share code, notes, and snippets.

@maxichrome
Last active November 16, 2020 15:49
Show Gist options
  • Select an option

  • Save maxichrome/b09dfcbe83b655c312d2ed48fde6a9d0 to your computer and use it in GitHub Desktop.

Select an option

Save maxichrome/b09dfcbe83b655c312d2ed48fde6a9d0 to your computer and use it in GitHub Desktop.
Recursively, synchronously read a directory in Node.js
/*
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
}
/*
*** 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