With nodejs, how to get all the files of a directory (including its subdirectories)

To find all the children files, we need to recursively traverse the directory.

Example code (synchronous)

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.

Example code (Asynchronous)

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
}
Posted on 2023-04-22