5

I have a following code in coffeescript to recursively list directories (converted from javascript):

fs = require 'fs'

walk = (dir, done) ->
  results = []
  fs.readdir dir, (err, list) ->
    return done(err) if err
    pending = list.length
    return done(null, results) unless pending
    list.forEach (file) ->
      file = "#{dir}\\#{file}"
      fs.stat file, (err, stat) ->
        if stat and stat.isDirectory()
          walk file, (err, res) ->
            results = results.concat(res)
            done null, results  unless --pending
        else
          results.push file
          done null, results  unless --pending

walk __dirname, (err, results) ->
  throw err if err
  console.log results

As you can see I am using list.forEach (file) -> and it's working. But when I try to replace it with for file in list then it doesn't work properly. What do I do wrong?

1
  • Can we see what the code looks like when you change it to for file in list? Commented Jul 19, 2012 at 18:50

1 Answer 1

10

You're defining a function in a loop. A common pitfall in JS. You'll need to close over the iterator.

for file in list then do (file) =>

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

2 Comments

The fat arrow is not necessary in this case, as there is no access to this inside the loop. Also, an alternative to using the do CoffeeScript construct, that just creates function and invokes it right there to create a new scope, is to do that yourself: for example: processFile file for file in list, where processFile does exactly the same as inside the loop. I think that alternative is clearer most of the time.
Thank a lot, it works just fine. As you advised I am using an alternative because it clearer

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.