adam
adam

Reputation: 1453

how to add all files from a certain type in array nodejs?

I am iterating over a folder and its sub folders and trying to add all the .jss files into an array:

function getJssFromDir(directory,arr) {
    fs.stat(directory,function (err, stats) {
        if (stats.isFile()) {
            //check if its jss file
            if (path.extname(directory) === '.jss') {
                arr.push(directory);
            }
        } else if (stats.isDirectory()) {
            fs.readdir(directory, function(err, files) {
                if (err) throw err;
                for (var i=0; i<files.length; i++) {
                    getJssFromDir(directory+'/'+files[i],arr);
                }
            });
        }
    }); 
}

then trying to print it and I see nothing:

var array = [];
getJssFromDir('c:/internet',array);
console.log(array);

what am i doing wrong when I try to print the array in the getJssFromDIR I see all the files that I want to add being added to the array.

Upvotes: 1

Views: 802

Answers (1)

fent
fent

Reputation: 18205

When you read a directory, you are reading the disk. That takes time. In node.js, any time of IO operation takes a callback because it does not get executed right away.

You will need to add callbacks to your getJssFromDir function and call it with a callback.

But since you are doing a recursive call, it can get complicated managing all the callbacks. Many libraries have already been made for this type of situation, I suggest findit

var array = [];
var finder = require('findit').find('c:/internet');

finder.on('file', function(file) {
  if (path.extname(directory) === '.jss') {
    array.push(file);
  }
});

finder.on('end', function() {
  console.log(array);
});

Upvotes: 1

Related Questions