Foreach数组并在回调中使用数组成员

时间:2013-04-24 07:29:37

标签: node.js coffeescript

我有一组远程文件地址。我只是用于foreach数组和foreach的主体,我开始HTTP GET请求数据下载。但是一切都是异步的,我需要知道文件名以将文件保存在请求回调中。

解决此问题的最佳做法是什么?

演示代码:

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"

谢谢!

2 个答案:

答案 0 :(得分:0)

你必须确定它的范围。使用这样的函数:

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

答案 1 :(得分:0)

在CoffeeScript中执行此操作的正确方法是do调用。将编码设置为'binary'也没有意义,只需创建额外的工作来从缓冲区和字符串来回转换数据。

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