Petr
Petr

Reputation: 224

What download images from remote url

I've array of url images. I need download asynchronous this images from remote url to my server.

EXAMPLE:

// 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); 

Upvotes: 0

Views: 275

Answers (1)

Corey Berigan
Corey Berigan

Reputation: 634

If you want it to asynchronously return anything you must use a callback pattern instead of returning a value from a function. With that said you also need a way for the final result callback to fire once all images have been loaded. I would suggest using a module like async and use the map function it provides. The map function will allow you to process an array and it gives back an array of results. Below is an example:

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); 
}); 

Upvotes: 2

Related Questions