Languages
[Edit]
EN

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

0 points
Created by:
Mahir-Bright
261

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

Practical example

Project structure:

directory/
 β”œβ”€β”€ one.txt
 └── directory2/
 |      └── two.json
 └── directory3/
        └── three.html

Code:Β 

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('C:\\directory'));
};

displayFiles();

Output:Β 

[
  'one.txt',
  'two.json',
  'three.html'
]

See also

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

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