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.
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'
]