Languages
[Edit]
EN

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

0 points
Created by:
Dirask Admin - Marwin
1460

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');
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);
};

console.log(getFilesFromDirectory('C:\directory'));

Output:Β 

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

See also

  1. Node.js - get files from directory (recursively) asynchronous 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