EN
Node.js - list files recursively from directory (synchronous mode)
3
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
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'
]
Β