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?
JavaScript Array forEach() The forEach() method calls a function for each element in an array. The forEach() method is not executed for empty elements.
The function keyword is eliminated in CoffeeScript. To define a function here, we have to use a thin arrow (->). Behind the scenes, the CoffeeScript compiler converts the arrow in to the function definition in JavaScript as shown below.
If you are looking to implement coffee script in html, take a look at this. You simple need to add a <script type="text/coffeescript" src="app. coffee"></script> to execute coffee script code in an HTML file.
The forEach method passes a callback function for each element of an array together with the following parameters: Current Value (required) - The value of the current array element. Index (optional) - The current element's index number. Array (optional) - The array object to which the current element belongs.
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) =>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With