title: Walking a directory with Node.js
body: <p>I've got a problem with this code in node.js. I want to recursively walk through a directory tree and apply the callback <code>action</code> to every file in the tree. This is my code at the moment:</p>
  
  <pre><code>var fs = require("fs");
  
  // General function
  var dive = function (dir, action) {
    // Assert that it's a function
    if (typeof action !== "function")
      action = function (error, file) { };
  
    // Read the directory
    fs.readdir(dir, function (err, list) {
      // Return the error if something went wrong
      if (err)
        return action(err);
  
      // For every file in the list
      list.forEach(function (file) {
        // Full path of that file
        path = dir + "/" + file;
        // Get the file's stats
        fs.stat(path, function (err, stat) {
          console.log(stat);
          // If the file is a directory
          if (stat &amp;&amp; stat.isDirectory())
            // Dive into the directory
            dive(path, action);
          else
            // Call the action
            action(null, path);
        });
      });
    });
  };
  </code></pre>
  
  <p>The problem is that in the <em>for each loop</em> stat is called for every file via the variable <code>path</code>. When the callback is called, <code>path</code> already has another value and so it <code>dive</code>s into the wrong directories or calls the <code>action</code> for the wrong files.</p>
  
  <p>Probably this problem could easily get solved by using <code>fs.statSync</code>, but this is not the solution I would prefer, since it is blocking the process.</p>