EN
Node.js - get list of filenames in directory
0 points
In this article, we would like to show you how to get a list of the names of all files (one level deep) in a specified directory in Node.js.
Asynchronous version:
xxxxxxxxxx
1
const fs = require('fs');
2
3
fs.readdir(pathToDirectory, { withFileTypes: true }, (error, files) => {
4
const filesInDIrectory = files
5
.filter((item) => item.isFile())
6
.map((item) => item.name);
7
8
console.log(filesInDIrectory);
9
});
Synchronous version:
xxxxxxxxxx
1
const fs = require('fs');
2
3
const filesInDIrectory = fs.readdirSync(pathToDirectory, { withFileTypes: true })
4
.filter((item) => item.isFile())
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('./', (error, files) => {
4
if (error) throw error;
5
console.log(files);
6
});
7
8
fs.readdir('./', { withFileTypes: true }, (error, files) => {
9
if (error) throw error;
10
const filesInDIrectory = files
11
.filter((item) => item.isFile())
12
.map((item) => item.name);
13
14
console.log(filesInDIrectory);
15
});
Output:
xxxxxxxxxx
1
[
2
'my_script.js'
3
]
Note:
The result of the operation will be a list of files on the first depth level - files in folders located in the directory we search will not be displayed.
The path'./'
is the directory where the executing script is located (in this case,Project
).