2016-07-24 64 views
1

請原諒我,因爲代碼雜亂無章。我還在學習。 我需要使用CSV文件中的URL掃描下載圖像。然而,我有2000+的網址與同一個域名,我不認爲服務器會讓我把所有東西都拉出去,因此我總是在一些圖片後出錯。問題,我需要解決 -
1)如何確保圖像完全下載,然後只有代碼移動到下一個網址
2)如何編寫更好的代碼
您的幫助表示讚賞。謝謝使用帶有URL掃描的節點請求下載帶有CSV的圖像

var csv = require('fast-csv'); 
var Promise = require('bluebird'); 
var fs = require('fs'); 
var request = require('request'); 
var path = "test.csv"; 

var promiseCSV = Promise.method(function(path, options) { 
    return new Promise(function(resolve, reject) { 
    var records = []; 
    csv 
     .fromPath(path, options) 
     .on('data', function(record) { 
     records.push(record); 
     }) 
     .on('end', function() { 
     resolve(records); 
     console.log('done'); 
     }); 
    }); 
}); 



var download = function(uri, filename, callback){ 
    request.head(uri, function(err, res, body){ 

    request(uri).pipe(fs.createWriteStream(filename)).on('close', callback); 
    }); 
}; 


promiseCSV(path).then(function (records) { 

for(i=0;i<records.length;i++) 
    {  
     download(records[i][0],'img/'+records[i][1], function(){ 

     }); 
    } 

}); 

回答

1

這會一次限制您的請求。另一種選擇是使用throttled-request來限制每單位時間的請求。

var i = 0; 
promiseCSV(path).then(function (records) { 
    next(); 
    function next(){ 
    download(records[i][0],'img/'+records[i][1], function(){ 
     i++; 
     if (i < records.length) next(); 
    }); 
    } 
}); 

而且,你的記錄變量超出範圍,則需要將其移出,以訪問:

var records = []; // move out to global scope to access from elsewhere 
var promiseCSV = Promise.method(function(path, options) { 
    return new Promise(function(resolve, reject) { 
    csv 
     .fromPath(path, options) 
     .on('data', function(record) { 
     records.push(record); 
     }) 
     .on('end', function() { 
     resolve(records); 
     console.log('done'); 
     }); 
    }); 
}); 
+0

謝謝你,夥計!它現在正在運行:) – user2982110