To find all the children files, we need to recursively traverse the directory.
const fs = require('fs')
const path = require('path')
function getFiles(dir) {
const files = []
fs.readdirSync(dir).forEach(file => {
let fullPath = path.join(dir, file)
if (fs.lstatSync(fullPath).isDirectory()) {
// access the subdirectory
files.push(...getFiles(fullPath))
} else {
files.push(fullPath)
}
})
return files
}
Notice the line files.push(...getFiles(fullPath))
. We recursively call the getFiles
function here.
const fs = require('fs')
const path = require('path')
async function getFiles(dir) {
const files = []
const items = await fs.promises.readdir(dir)
for (const file of items) {
const fullPath = path.join(dir, file)
if ((await fs.promises.lstat(fullPath)).isDirectory()) {
files.push(...(await getFiles(fullPath)))
} else {
files.push(fullPath)
}
}
return files
}