Count files in a directory with nodejs

In this post, you will learn how to count files in a directory with nodejs.
When working with files and directories, the built in fs module in nodejs provides an api for interacting with the file system. All file system have asynchronous and synchronous nature.
The fs module in Nodejs comes with a method readadir that enable us to read the content in a directory.
The code below get and print the total number of files in a directory.
var fs = require('fs'); fs.readdir( 'path/to/your/folder', (error, files) => {
let totalFiles = files.length; // return the number of files
console.log(totalFiles); // print the total number of files
});
If your Node.js package does not support JavaScript arrow function, you can use the normal JavaScript function.
var fs = require('fs'); fs.readdir( 'path/to/your/folder', function(error, files) {
var totalFiles = files.length; // return the number of files
console.log(totalFiles); // print the total number of files
});
Please change the path to your folder
to the folder you want to access.
The readdir is a method in fs module.
readdir is asychronous in nature.
It allows three parameters (path[, options], callback).
The first parameter — path
is where we specify the path to the folder we want to access.
The second parameter is optional. This is where we specify some option like encoding.
The callback gets two arguments (err, files)
where files
is an array of the names of the files in the directory excluding '.'
and '..'
.
.length is a property for getting the length of an array.