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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.