Languages
[Edit]
EN

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

0 points
Created by:
Mahir-Bright
1281

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)
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

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