Tuesday, 2 May 2017

Node.js async function creating a callback void

I created a async function that iterates in the directories from a given path and return a collection of fileObj, a simple object with properties.

It was working with my file hierarchy, but now I'm testing the function on more complex folders like my steam directory and it just stops in the nested callback after 3s :

function getDirectoriesASync(srcpath, done) {
var list = [];

fs.readdir(srcpath, function(err, files) {
  if (err) return done(err);

  var pending = files.length;

  if (--pending <= 0) return done(null, list);

  files.forEach(function(file) { 
    var fileObj = {};
    fileObj.name = file;
    fileObj.path = path.join(srcpath, file);

    fs.stat(fileObj.path, function(err, stat) {
        //if (err) return done(err);
        if (err) console.log(err);

      if (stat && stat.isDirectory()) {
          fileObj.isDirectory = true;

          getDirectoriesASync(fileObj.path, function(err, res) {
            if (err) console.log(err);
            fileObj.subdir = res;
            list.push(fileObj);

            console.log('DONE DIR ' + fileObj.path + '--pending : ' + pending );
            if (--pending <= 0) {return done(null, list); }
          });
      } else {
        var sizeInMb = stat.size;

        sizeInMb = sizeInMb / 1000000;
        fileObj.size = (sizeInMb >= 1000) ? (sizeInMb / 1000).toFixed(2) + " G" : sizeInMb.toFixed(2) + " Mb";
        fileObj.isFile = true;

        list.push(fileObj);

        if (--pending <= 0) return done(null, list);
      }
    });
  });
});

};

it's my first async function, I don't know if it's optimised, but my Node.js process when "stuck" is ath 0%.

Any idead and advice? Tank you!



via Just4lol

No comments:

Post a Comment