EN
Node.js - list all directories in directory
0 points
In this article, we would like to show you how to get a list of the names of all directories in a specified directory in Node.js.
Quick solution:
xxxxxxxxxx
1
const fs = require('fs');
2
3
fs.readdir(pathToDirectory, { withFileTypes: true }, (error, files) => {
4
const directoriesInDIrectory = files
5
.filter((item) => item.isDirectory())
6
.map((item) => item.name);
7
8
console.log(directoriesInDIrectory);
9
});
Synchronous version:
xxxxxxxxxx
1
const fs = require('fs');
2
3
const directoriesInDIrectory = fs.readdirSync(pathToDirectory, { withFileTypes: true })
4
.filter((item) => item.isDirectory())
5
.map((item) => item.name);
Projects structure
xxxxxxxxxx
1
Project/
2
|
3
+-- my_directory/
4
| |
5
| +-- file.json
6
|
7
+-- my_script.js
my_script.js
xxxxxxxxxx
1
const fs = require('fs');
2
3
fs.readdir('./', { withFileTypes: true }, (error, files) => {
4
if (error) throw error;
5
const directoriesInDIrectory = files
6
.filter((item) => item.isDirectory())
7
.map((item) => item.name);
8
9
console.log(directoriesInDIrectory);
10
});
Output:
xxxxxxxxxx
1
[
2
'my_directory'
3
]