1

我有一系列远程文件地址。我只是使用 for in 到 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"

谢谢!

4

2 回答 2

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
于 2013-04-24T08:08:02.383 回答
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
于 2013-04-25T04:32:55.827 回答