2013-04-24 68 views
1

我有一組遠程文件地址。我只是用於在foreach數組和foreach的主體中,我開始HTTP GET請求數據下載。但是,一切都是異步的,我需要知道文件名以將文件保存在請求回調中。Foreach數組並在回調中使用數組成員

解決此問題的最佳做法是什麼?

演示代碼:

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" 

謝謝!

+0

什麼問題?你問如何將'url.com/file.png'轉換爲'file.png'? – Eric 2013-04-24 07:52:08

+0

不,根據writeFileSync我需要獲取原始變量「文件」的值。但一切都是異步的,所以變量「文件」將只填寫最後的文件名。 – 2013-04-24 07:55:05

+0

你確定嗎?我認爲coffeescript for loops使用閉包來防止這種問題。 – Eric 2013-04-24 07:57:27

回答

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 
+2

爲什麼不使用'do'?查看本節的底部:http://coffeescript.org/#loops – 2013-04-24 15:50:35

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