Short, Modern and Efficient:
import {readdir} from 'node:fs/promises'
import {join} from 'node:path'
const walk = async (dirPath) => Promise.all(
await readdir(dirPath, { withFileTypes: true }).then((entries) => entries.map((entry) => {
const childPath = join(dirPath, entry.name)
return entry.isDirectory() ? walk(childPath) : childPath
})),
)
Special thank to Function for hinting: {withFileTypes: true}.
This automatically keeps tree-structure of the source directory (which you may need). For example if:
const allFiles = await walk('src')
then allFiles would be a TREE like this:
[
[
'src/client/api.js',
'src/client/http-constants.js',
'src/client/index.html',
'src/client/index.js',
[ 'src/client/res/favicon.ico' ],
'src/client/storage.js'
],
[ 'src/crypto/keygen.js' ],
'src/discover.js',
[
'src/mutations/createNewMutation.js',
'src/mutations/newAccount.js',
'src/mutations/transferCredit.js',
'src/mutations/updateApp.js'
],
[
'src/server/authentication.js',
'src/server/handlers.js',
'src/server/quick-response.js',
'src/server/server.js',
'src/server/static-resources.js'
],
[ 'src/util/prompt.js', 'src/util/safeWriteFile.js' ],
'src/util.js'
]
Flat it, if you don't want tree-structure:
allFiles.flat(Number.POSITIVE_INFINITY)
[
'src/client/api.js',
'src/client/http-constants.js',
'src/client/index.html',
'src/client/index.js',
'src/client/res/favicon.ico',
'src/client/storage.js',
'src/crypto/keygen.js',
'src/discover.js',
'src/mutations/createNewMutation.js',
'src/mutations/newAccount.js',
'src/mutations/transferCredit.js',
'src/mutations/updateApp.js',
'src/server/authentication.js',
'src/server/handlers.js',
'src/server/quick-response.js',
'src/server/server.js',
'src/server/static-resources.js',
'src/util/prompt.js',
'src/util/safeWriteFile.js',
'src/util.js'
]
fs.globandfs.globSync. A simplefs.globSync("./**/*")gets you exactly the kind of flat array of file paths that you can thenmap,filter, etc. etc. that this question was about. With the added benefit of being able to pre-filter by using an appropriate globbing pattern. And it only took thirteen years to get added to Node =D