1

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!

3
  • What's the problem? Are you asking how to convert url.com/file.png to file.png? Commented Apr 24, 2013 at 7:52
  • No, on line with writeFileSync I needs to get value of original variable "file". But everything is async, so variable "file" will be filled only with last filename. Commented Apr 24, 2013 at 7:55
  • Are you sure? I thought coffeescript for loops used closures to prevent this kind of problem. Commented Apr 24, 2013 at 7:57

2 Answers 2

0

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
Sign up to request clarification or add additional context in comments.

1 Comment

Why not use do? See the bottom of this section: coffeescript.org/#loops
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.