Categories
JavaScript Answers

How to count the number of files in a directory using JavaScript and Node.js?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *