我有一系列网址图片。我需要将此图像从远程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)
如果您希望它异步返回任何内容,则必须使用回调模式,而不是从函数返回值。有了这个说,你还需要一种方法,一旦加载了所有图像,最终结果回调就会触发。我建议使用像async这样的模块并使用它提供的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);
});