1

リモートファイルアドレスの配列があります。foreach 配列に for を使用し、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

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 に答える
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 に答える