Languages
[Edit]
EN

Node.js - get files from directory (recursively)

0 points
Created by:
Blythe-F
290

In this article, we would like to show you how to get all files from a directory (including subdirectories) in Node.js.

Note:

Check out this article for a practical example of using the code below - link.

Synchronous version:

const fs = require('fs');
const path = require('path');

const getFilesFromDirectory = (directoryPath) => {
    const filesInDirectory = fs.readdirSync(directoryPath);
    const files = filesInDirectory.map((file) => {
        const filePath = path.join(directoryPath, file);
        const stats = fs.statSync(filePath);

        if (stats.isDirectory()) {
            return getFilesFromDirectory(filePath);
        } else {
            return filePath;
        }
    });

    return files.filter((file) => file.length); // return with empty arrays removed
};

console.log(getFilesFromDirectory('/path/to/directory'));

Asynchronous version:

const fs = require('fs/promises');
const path = require('path');

const getFilesFromDirectory = async (directoryPath) => {
    const filesInDirectory = await fs.readdir(directoryPath);
    const files = await Promise.all(
        filesInDirectory.map(async (file) => {
            const filePath = path.join(directoryPath, file);
            const stats = await fs.stat(filePath);
            
            if (stats.isDirectory()) {
                return getFilesFromDirectory(filePath);
            } else {
                return filePath;
            }
        })
    );

    return files.filter((file) => file.length); // return with empty arrays removed
};

const displayFiles = async () => {
    console.log(await getFilesFromDirectory('/path/to/directory'));
};

displayFiles();

See also

  1. Node.js - get files from directory (recursively) example

Node.js - file system module

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join