1

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?

  • First parameter in `fs.readdir` callback is error not file list. https://nodejs.org/api/fs.html#fs_fs_readdir_path_options_callback – ponury-kostek Sep 28 '20 at 17:40
  • @ponury-kostek I corrected it here. – shikha sharma Sep 28 '20 at 17:45
  • Excluding the `then` part of the promise means that you are never using the `obj` anywhere and not calling a `count` method either, so it's unclear how an assertion error would come from that part? Also, what is the exact error message? – Bergi Sep 28 '20 at 18:24
  • @Bergi I've included it in my original code.Here,due to the long length of code i excluded it. – shikha sharma Sep 29 '20 at 09:51

1 Answers1

0

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

Plantera
  • 36
  • 8