kenneth koontz
kenneth koontz

Reputation: 869

recursively watch a directory with node.js api

I'm trying to recursively watch a directory and I'm stumbling upon a namespace issue.

My code looks like this:

for (i in files) {
    var file = path.join(process.cwd(), files[i]);
    fs.lstat(file, function(err, stats) {
        if (err) {
            throw err;
        } else {
            if (stats.isDirectory()) {
                // Watch the directory and traverse the child file.
                fs.watch(file);
                recursiveWatch(file);
            }   
        }   
    }); 
}

It appears that I'm only watching the last directory stat'd. I believe the problem is that the loop finishes before the lstat callback is finished. So every time the lstat callback's are called, file = . How do I address this? Thank you!

Upvotes: 2

Views: 4206

Answers (2)

thSoft
thSoft

Reputation: 22660

There is the node-watch package for this purpose.

Upvotes: 0

Dan D.
Dan D.

Reputation: 74685

You might to consider using: (assuming ES5 and that files is an Array of filenames)

files.forEach(function(file) {
  file = path.join(process.cwd(), file);
  fs.lstat(file, function(err, stats) {
    if (err) {
      throw err;
    } else {
      if (stats.isDirectory()) {
        // Watch the directory and traverse the child file.
        fs.watch(file);
        recursiveWatch(file);
      }
    }
  });
});

Upvotes: 3

Related Questions