Sometimes, we want to count the number of files in a directory using JavaScript and Node.js.
In this article, we’ll look at how to count the number of files in a directory using JavaScript and Node.js.
How to count the number of files in a directory using JavaScript and Node.js?
To count the number of files in a directory using JavaScript and Node.js, we can use the fs.readdir
with the irectory to get the array of files data in the directory.
Then we can use the length
property to get the number of files in the directory.
For instance, we write:
const { promises: fs } = require('fs');
const dir = '/';
const getNumFiles = async (dir) => {
const files = await fs.readdir(dir)
console.log(files.length)
}
getNumFiles(dir)
to define the getNumFiles
function that takes the dir
directory string.
In the function, we call fs.readdir
with dir
to read the files data in dir
into an array.
Then we get the number of files from the length
property.
Conclusion
To count the number of files in a directory using JavaScript and Node.js, we can use the fs.readdir
with the irectory to get the array of files data in the directory.
Then we can use the length
property to get the number of files in the directory.