Nodejs request模块有用过的吗

Nodejs request模块有用过的吗

几百次循环会出现十几个报错 Error: socket hang up或者 Error: read ECONNRESET 实现通过配置文件批量下载图片 该怎么避免 socket 报错 http.request({url:file_url},function (error, response, body) { if (!response||error) { fs.writeFile(path.join(logsPath,‘uploadpic.log’),file_name+"||"+error+"||"+common_time+"\n",{encoding:‘utf8’,flag: ‘a+’}); } }).pipe(fs.createWriteStream(path.join(download_path+"/"+cata,file_name)));


6 回复

当然可以。关于你在Node.js中使用request模块时遇到的socket hang upECONNRESET错误,这通常是由于网络连接问题或服务器响应问题导致的。为了更好地处理这些情况,并且有效地实现从配置文件批量下载图片的功能,我们可以使用request模块结合一些异常处理机制来增强代码的健壮性。

示例代码

首先,确保你已经安装了request模块:

npm install request

然后,你可以编写如下的Node.js脚本来实现你的需求:

const fs = require('fs');
const path = require('path');
const request = require('request');

// 假设你有一个配置文件,其中包含图片的URL列表
const configFilePath = path.join(__dirname, 'config.json');

// 读取配置文件
const config = JSON.parse(fs.readFileSync(configFilePath));

// 下载图片的函数
const downloadImage = (fileUrl, downloadPath, fileName) => {
    const downloadPathWithFile = path.join(downloadPath, fileName);
    
    request(fileUrl)
        .on('error', function(error) {
            console.error(`Error downloading ${fileUrl}:`, error.message);
            // 记录错误日志
            fs.appendFileSync(
                path.join(__dirname, 'uploadpic.log'),
                `${fileName}||${error.message}||${new Date().toISOString()}\n`,
                { encoding: 'utf8' }
            );
        })
        .pipe(fs.createWriteStream(downloadPathWithFile))
        .on('close', () => {
            console.log(`${fileName} downloaded successfully.`);
        });
};

// 遍历配置文件中的每个图片URL并下载
config.forEach((item) => {
    downloadImage(item.url, path.join(__dirname, 'downloaded_images'), item.fileName);
});

解释

  1. 读取配置文件:我们假设配置文件是一个JSON文件,其中包含一个数组,数组中的每个对象都包含图片的URL和文件名。
  2. 下载函数:定义了一个downloadImage函数,它接收图片的URL、下载路径以及文件名作为参数。该函数使用request模块发起HTTP请求,将响应体写入到指定路径。
  3. 错误处理:通过监听error事件来捕获任何下载过程中发生的错误,并将错误信息记录到日志文件中。
  4. 遍历配置:最后,遍历配置文件中的所有项目,并调用downloadImage函数来下载每张图片。

这种方法可以帮助你更有效地管理批量下载过程中的错误,并提高程序的稳定性。


对方hold不住你的频繁骚扰,断开了。 速则不达。限制下吧,每次批量操作一定数量。

把错误的链接,记录下来,然后重新下载吧。。。

没办法 只能这么搞了 也没提供最大下载个数什么的 弱爆了

用async 限制每次只能下几个~

针对你提到的 socket hang up 或者 read ECONNRESET 错误,可以使用 request 模块来处理HTTP请求,并且结合错误处理逻辑来提高代码的健壮性。request 模块提供了一个更为简洁的API来处理这些常见问题。

首先,确保安装了 request 模块:

npm install request

下面是一个简单的示例代码,展示如何通过配置文件批量下载图片,并处理可能出现的网络错误:

const fs = require('fs');
const request = require('request');

// 假设你的配置文件是一个JSON文件,包含一个图片URL数组
const config = JSON.parse(fs.readFileSync('./config.json', 'utf8'));
const download_path = './downloads';
const logsPath = './logs';

if (!fs.existsSync(download_path)) {
    fs.mkdirSync(download_path);
}

if (!fs.existsSync(logsPath)) {
    fs.mkdirSync(logsPath);
}

for (const file of config.images) {
    const { file_url, file_name } = file;
    const cata = 'category'; // 根据实际需求修改

    const filePath = path.join(download_path, cata, file_name);

    request(file_url)
        .on('error', function (err) {
            // 处理请求错误
            fs.appendFile(
                path.join(logsPath, 'uploadpic.log'),
                `${file_name}||${err.message}||${new Date().toISOString()}\n`,
                (err) => {
                    if (err) console.error('Error writing to log file:', err);
                }
            );
        })
        .on('end', () => {
            console.log(`Downloaded ${file_name}`);
        })
        .pipe(fs.createWriteStream(filePath));
}

解释

  1. 配置文件:假设你有一个配置文件(例如 config.json),它包含一个数组,数组中每个对象都有一个 file_urlfile_name 属性。
  2. 错误处理:在请求中添加了 on('error') 事件处理器来捕获任何错误,并将错误信息写入日志文件。
  3. 目录创建:在下载文件之前,检查并创建必要的目录结构(download_pathlogsPath)。
  4. 批量下载:遍历配置中的每个图片URL,发起下载并将结果存储在指定路径。

通过这种方式,你可以更好地管理和监控下载过程中的错误情况。

回到顶部