Sometimes, we want to get a list of the names of all files present in a directory in Node.js.
In this article, we’ll look at how to get a list of the names of all files present in a directory in Node.js.
How to get a list of the names of all files present in a directory in Node.js?
To get a list of the names of all files present in a directory in Node.js, we can call the readdir
method.
For instance, we write
const testFolder = './folder/path';
const fs = require('fs');
fs.readdir(testFolder, (err, files) => {
files.forEach(file => {
console.log(file);
});
});
to call fs.readdir
with the testFolder
folder path string and a callback that has all the files
in an array.
In the callback, we call files.forEach
to loop through each file entry.
Conclusion
To get a list of the names of all files present in a directory in Node.js, we can call the readdir
method.