title: Node.js: problem with variable scope in callback
body: <pre><code>var result = { controllers: [], views: [], models: [] };
  var dirs = ['controllers', 'views', 'models'];
  
  dirs.forEach(function(dirname) {
      fs.readdir('./' + dirname, function(err, res) {
          if (err) throw err;
          result[dirname] = res;
          // #2
      });
  });
  
  // #1
  </code></pre>
  
  <p>In this snippet of code, having <code>console.log(result);</code> running at #1 (see above), empty controller, views, and models arrays just as initialized will be logged. However, I need the loop to fill the arrays with corresponding file names read via <code>fs</code>.</p>
  
  <p><code>console.log(result);</code> at #2 will log the <code>result</code> object filled with the desired values after the third iteration.</p>
  
  <p>I believe this has something to do with the asynchronous nature of Node.js / JavaScript callbacks. Please forgive me if I'm not understanding how JavaScript variable scopes and async methods work, I'm all new to this.</p>