Ankit Parmar
Ankit Parmar

Reputation: 790

Get length of only files not including folder

Get the length of the files not including folder.

const fs = require('fs');
fs.readdir(process.cwd(), function(err, files) {
   console.log(files.length);
}

I have written the code but code includes the folder. I don't want to count the folder

Upvotes: 0

Views: 49

Answers (2)

Touseef Murtaza
Touseef Murtaza

Reputation: 1956

Retriving files count in a directory can be achieved by using fs.

const fs = require('fs');
const dir = './directory';
fs.readdir(dir, (err, files) => {
  console.log(files.length);
});

Upvotes: 0

Vivek
Vivek

Reputation: 2755

The fs.readdir function fetches the list of files and folders within the given directory. In order to filter only files from the list and ignore directories, you need to implement an additional check using the fs.statSync("path").isFile() function.

The below code should give you the desired results.

const fs = require('fs');
fs.readdir(process.cwd(), function(err, contents) {
  var files = [];
  contents.forEach(function(f) {
    if(fs.statSync(f).isFile()) {
      files.push(f);
    }
  });
  console.log(files.length);
});

Upvotes: 1

Related Questions