2012-04-27 73 views
0

我想让http.get下载图像文件列表。 我有一个for循环遍历列表,并用代表保存位置的字符串填充变量file_savedest。 因此,http.get在每次循环迭代时都被调用,我如何将file_savedest提供给http.get,以便知道要下载和保存的文件。http.get循环下载文件列表

var file_savedest = dir+"/"+iname; 

    http.get(options, function(res){ 
     var imagedata = ''; 
     res.setEncoding('binary'); 

     res.on('data', function(chunk){ 
      imagedata += chunk 
     }); 

     res.on('end', function(){ 
      fs.writeFile(file_savedest, imagedata, 'binary', function(err){ 
       if (err){ 
        console.log(err); 
       } else { 
        console.log("File:" + file_savedest + " saved"); 
       } 
      }); 
     }); 
    }); 

回答

2

使用closure

(function(file_savedest){ 
    http.get(options, function(res){ 
     var imagedata = ''; 
     res.setEncoding('binary'); 

     res.on('data', function(chunk){ 
      imagedata += chunk 
     }); 

     res.on('end', function(){ 
      fs.writeFile(file_savedest, imagedata, 'binary', function(err){ 
       if (err){ 
        console.log(err); 
       } else { 
        console.log("File:" + file_savedest + " saved"); 
       } 
      }); 
     }); 
    }); 
}(dir+"/"+iname));