I have array of remote files address. I simply use for in to foreach array and in body of foreach, I starting HTTP GET request for data download. But everything is async and I need to know filename to save the file in request callback.
What is the best practice to solve this?
Demo code:
files = ["url.com/file.png", "url.com/file.doc"]
for file in files
  req = http.get file, (response) =>
    response.setEncoding 'binary'
    body = ""
    response.on "data", (chunk) =>
      body += chunk
    response.on "end", () =>
      #Here I needs to know the file name to save it
      fs.writeFileSync @currentFolder + "/Files/" + file, body, "binary"
Thank you!
				
				You have to scope it. Use a function like this:
files = ["url.com/file.png", "url.com/file.doc"]
for file in files
    ((file) ->
        req = http.get file, (response) =>
            response.setEncoding 'binary'
            body = ""
        response.on "data", (chunk) =>
            body += chunk
        response.on "end", () =>
            fs.writeFileSync @currentFolder + "/Files/" + file, body, "binary"
    ).call @, file
				
			The proper way to do this in CoffeeScript is with a do call. Also setting the encoding to 'binary' makes no sense and just creates extra work to convert the data back and forth from a Buffer and a string.
for file in files
  do (file) =>
    req = http.get file, (response) =>
      parts = []
      response.on "data", (chunk) =>
        parts.push chunk
      response.on "end", () =>
        body = Buffer.concat parts
        fs.writeFileSync @currentFolder + "/Files/" + file, body