gpt4 book ai didi

javascript - Node.js 使用请求模块从 url 下载图像给出 URI 错误

转载 作者:行者123 更新时间:2023-12-02 20:53:50 26 4
gpt4 key购买 nike

我正在循环下载图像,当我将循环设置为for (var i = 0; i < 100; i++) {时我下载图像没有问题。但一旦我改变我的 i范围超过 99(包括 100),所以类似:for (var i = 100; i < 200; i++) {for (var i = 0; i < 200; i++) {我收到一个错误。这是我的代码:

var fs = require('fs');

var request = require('request');

var download = function(uri, filename, callback){
request.head(uri, function(err, res, body){
request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
});
};

var arrLength = allProducts.length;

for (var i = 0; i < arrLength; i++) {

let imgName = allProducts[i].code;
let imgUrl = allProducts[i].nofrillsImgLink

download(`${imgUrl}`, `./allProductsImg/${imgName}.png`, function(){
});
};

这是我收到的错误:

events.js:287
throw er; // Unhandled 'error' event
^

Error: Invalid URI "undefined"
at Request.init (.../node_modules/request/request.js:273:31)
at new Request (.../node_modules/request/request.js:127:8)
at request (.../node_modules/request/index.js:53:10)
at Request._callback (.../downloadImg.js:7:5)
at self.callback (.../node_modules/request/request.js:185:22)
at Request.emit (events.js:310:20)
at Request.init (.../node_modules/request/request.js:273:17)
at new Request (.../node_modules/request/request.js:127:8)
at request (.../node_modules/request/index.js:53:10)
at Function.head (.../node_modules/request/index.js:61:12)
Emitted 'error' event on Request instance at:
at Request.init (.../node_modules/request/request.js:273:17)
at new Request (.../node_modules/request/request.js:127:8)
[... lines matching original stack trace ...]
at Function.head (.../node_modules/request/index.js:61:12)

最佳答案

您可以更改此代码

var download = function(uri, filename, callback){
request.head(uri, function(err, res, body){
request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
});
};

var download = function(uri, filename, callback){
if(uri !== undefined){
request.head(uri, function(err, res, body){
request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
});
}
};

关于javascript - Node.js 使用请求模块从 url 下载图像给出 URI 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61537508/

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