EN
Node.js - get files from directory (recursively) asynchronous example
0 points
In this article, we would like to show you how to get all files from a directory (including subdirectories) in Node.js.
Project structure:
xxxxxxxxxx
1
directory/
2
├── one.txt
3
└── directory2/
4
| └── two.json
5
└── directory3/
6
└── three.html
Code:
xxxxxxxxxx
1
const fs = require('fs/promises');
2
const path = require('path');
3
4
const getFilesFromDirectory = async (directoryPath) => {
5
const filesInDirectory = await fs.readdir(directoryPath);
6
const files = await Promise.all(
7
filesInDirectory.map(async (file) => {
8
const filePath = path.join(directoryPath, file);
9
const stats = await fs.stat(filePath);
10
11
if (stats.isDirectory()) {
12
return getFilesFromDirectory(filePath);
13
} else {
14
return filePath;
15
}
16
})
17
);
18
return files.filter((file) => file.length); // return with empty arrays removed
19
};
20
21
const displayFiles = async () => {
22
console.log(await getFilesFromDirectory('C:\\directory'));
23
};
24
25
displayFiles();
Output:
xxxxxxxxxx
1
[
2
'one.txt',
3
'two.json',
4
'three.html'
5
]