0

Here's the code I use to browse a directory :

var path = 'D:/Syslog/live';
listDir(path);

function listDir (path) {
    fs.readdir(path, function(err, files)
    {
        console.log(files);
        for( i = 0; i < files.length; i++)
        {
            var fullPath = path + "/" + files[i];
            fs.stat(fullPath, function(err, stats){
               if (stats.isDirectory())
               {
                   listDir(fullPath);
               } else
               {
                   console.log(files[i]);
               }
               });
        }
    });
}

When I debug and use the variable fullPath it works fine, if I use files[i] (which is declared in the level, i is undefined

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142

1 Answers1

2

As it's an asynchronous loop, i is iterating much faster than the rest of the code. You can use an anonymous closure function to freeze i within the loop.

Have a look at closures.

The popular async library is good for this sort of stuff too.

function listDir(path) {
    fs.readdir(path, function(err, files) {
        console.log(files);
        for (i = 0; i < files.length; i++) {
            (function(i) {
                var fullPath = path + "/" + files[i];
                fs.stat(fullPath, function(err, stats) {
                    if (stats.isDirectory()) {
                        listDir(fullPath);
                    } else {
                        console.log(files[i]);
                    }
                });
            })(i);
        }
    });
}

If you were using the async library, it'd look similar to this

var async = require('async');

function listDir(path) {
    fs.readdir(path, function(err, files) {
        console.log(files);
        async.each(files, function(file, callback) {
            var fullPath = path + "/" + file;
            fs.stat(fullPath, function(err, stats) {
                if (stats.isDirectory()) {
                    listDir(fullPath);
                } else {
                    console.log(file);
                }
                callback();
            });
        });
    });
}

Both tested and working.

Community
  • 1
  • 1
Ben Fortune
  • 31,623
  • 10
  • 79
  • 80