gpt4 book ai didi

node.js - 使用 Node 请求和 URL 扫描从 CSV 下载图像

转载 作者:太空宇宙 更新时间:2023-11-04 00:37:04 26 4
gpt4 key购买 nike

请原谅我,代码很乱。我还在学习。我需要从 CSV 文件下载带有 URL 扫描的图像。然而,我有 2000 多个具有相同域的 URL,而且我认为服务器不会让我一次性提取所有内容,因此在某些图像之后我总是会遇到错误。我需要解决的问题 -
1) 如何确保图像完全下载,然后只有代码移动到下一个 URL
2) 如何编写更好的代码
非常感谢您的帮助。谢谢您

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(){

});
}

});

最佳答案

这会将您的请求一次限制为一个。另一种选择是使用 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');
});
});
});

关于node.js - 使用 Node 请求和 URL 扫描从 CSV 下载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38551506/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com