2016-11-23 8 views
0

私はURLイメージの配列を持っています。私は私のサーバーにリモートURLから非同期にこのイメージをダウンロードする必要があります。リモートURLからのダウンロードイメージ

例:あなたはそれを非同期あなたの代わりに、関数から値を返すのコールバックパターンを使用しなければならない何かを返したい場合は

// i need this function return array localfiles after download 

function someFunctionAsDownloadedRemoteIMages(arrayOfRemoteUrls){ 
    localImages = []; 
    arrayOfRemoteUrls.forEach(function(url){ 
     request.head(url, function(err, res, body){ 
      newImageName = randomInt(100000, 999999); 
      var filename = 'catalog/import/'+newImageName+'.jpg'; 

      request(url, {encoding: 'binary'}, function(error, response, body) { 
       fs.writeFile('image/'+filename, body, 'binary', function (err) { 
       if(err) 
        return; 
       localImages.push(filename); 
       }); 
      }); 
     }); 
    }); 
} 

var remoteImagesArray = ["http://example.com/1.jpg", "http://example.com/1444.jpg","http://example.com/ddsgggg.jpg"]; 

localImagesArray = someFunctionAsDownloadedRemoteIMages(remoteImagesArray); 

someFunctionProccess(localImagesArray); 
+0

問題は何ですか? –

答えて

2

。それで、すべての画像がロードされたら、最終的な結果コールバックのための方法も必要です。私は非同期のようなモジュールを使用し、それが提供するmap関数を使用することをお勧めします。 map関数を使用すると配列を処理し、結果の配列を返します。以下はその例です:

var async = require('async'); 
var fs = require('fs'); 
var request = require('request'); 

function processUrl(url, callback){ 
    request.head(url, function(err, res, body){ 
      var newImageName = randomInt(100000, 999999); 
      var filename = 'catalog/import/'+newImageName+'.jpg'; 

      request(url, {encoding: 'binary'}, function(error, response, body) { 
       fs.writeFile('image/'+filename, body, 'binary', function (err) { 
       if(err) return callback(err); 
       callback(null,filename); 
       }); 
      }); 
     }); 
} 

function someFunctionAsDownloadedRemoteIMages(arrayOfRemoteUrls, callback){ 
    async.map(arrayOfRemoteUrls, processUrl, callback); 
} 



var remoteImagesArray = ["http://example.com/1.jpg", "http://example.com/1444.jpg","http://example.com/ddsgggg.jpg"]; 

someFunctionAsDownloadedRemoteIMages(remoteImagesArray, function(err, localImagesArray){ 
    if(err) //handle it 
    someFunctionProccess(localImagesArray); 
}); 
関連する問題