To count files present in a directory with specific extension in node.js

1.5k Views Asked by At

In a given task,I need to count file with extensions such as '.js','.txt' and other remaining extensions by using promise.

const fs = require("fs");
const path = require("path");

function fun(pathTodirectory) {
  return new Promise(resolve => {
    fs.readdir(pathTodirectory, (error, files) => {
      if (error) {
        reject("Error occured");
      }
      else {
        var obj = {
          countJs: function () {
            var count = 0;
            for (var i = 0; i < files.length; i++) {
              if (path.extname(files[i]) === ".js") {
                count++;
              }
            }
            return count;
          },
          countTxt: function () {
            var count = 0;
            for (var i = 0; i < files.length; i++) {
              if (path.extname(files[i]) === ".txt") {
                count++;
              }
            }
            return count;
          },
          count: function () {
            var count = 0;
            for (var i = 0; i < files.length; i++) {
              if (path.extname(files[i]) !== ".js" && path.extname(files[i] !== ".txt")) {
                count++;
              }
            }
            return count;
          },
          files: files //will print list of all files in form of array.
        }
        resolve(obj);
      }
    });
  });
}
//then part for promise.

This is my code so far,I'm getting problem in my code.The count part in not working and giving assertion error in console. I need to resolve in form of object only. How do i effectively do this?

1

There are 1 best solutions below

0
On

You never define path anywhere in the function. Unless you're defining it somewhere else that'll cause your error.