Languages
[Edit]
EN

Node.js - list files recursively from directory (synchronous mode)

3 points
Created by:
lena
714

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

Practical example

Note: the source code was tested under Windows.

Directory structure:

C:/directory/
    β”œβ”€β”€ text.txt
    β”œβ”€β”€ resources/
    β”‚    └── data.json
    └── pages/
         └── index.html

Source code:Β 

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

const listFiles = (directoryPath, filesPaths = []) => {
    for (const fileName of fs.readdirSync(directoryPath)) {
        const filePath = path.join(directoryPath, fileName);
        const fileStat = fs.statSync(filePath);
        if (fileStat.isDirectory()) {
            listFiles(filePath, filesPaths);
        } else {
            filesPaths.push(filePath);
        }
    }
    return filesPaths;
};


// Usage example:

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

Output:Β 

[
    'C:\\directory\\readme.txt',
    'C:\\directory\\pages\\index.html',
    'C:\\directory\\resources\\data.json'
]

Β 

See also

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

Alternative titles

  1. Node.js - get all files recursively in directory (synchronous mode)
  2. Node.js - get files recursively from directory (synchronous mode)
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