如何在 Node.js 中使用 axios 配置代理并實(shí)現(xiàn)圖片并發(fā)下載
一、創(chuàng)建 Axios 實(shí)例
可以創(chuàng)建一個 axiosConfig.ts 文件用于創(chuàng)建和更新相關(guān)實(shí)例:
// server/utils/axiosConfig.ts
const axios = require("axios");
const { HttpsProxyAgent } = require('https-proxy-agent');
// axios 實(shí)例
let axiosInstance = null;
// 代理表單(可以從數(shù)據(jù)庫讀取相關(guān)配置)
let proxyParams = {
state: true,
host: "127.0.0.1",
port: 10809,
protocol: "http",
username: "",
password: ""
};
// 創(chuàng)建 axios 實(shí)例
const createAxiosInstance = () => {
// 判斷是否開啟代理
const useProxy = proxyParams['state'] == true;
let axiosConfig = {
timeout: 5000
};
// 啟用代理服務(wù)
if (useProxy && proxyParams) {
const agent = new HttpsProxyAgent({
host: proxyParams.host,
port: proxyParams.port,
protocol: proxyParams.protocol,
});
axiosConfig['httpsAgent'] = agent;
}
// 代理服務(wù)器 用戶名、密碼
if (useProxy && proxyParams['username'] && proxyParams['password']) {
axiosConfig['auth'] = {
username: proxyParams['username'],
password: proxyParams['password']
};
}
axiosInstance = axios.create(axiosConfig);
}
// 獲取 Axios 實(shí)例
const getAxiosInstance = () => {
if (!axiosInstance) {
createAxiosInstance();
}
return axiosInstance;
}
// 更新 Axios 實(shí)例
const updateAxiosInstance = () => {
createAxiosInstance();
}
module.exports = {
getAxiosInstance,
updateAxiosInstance
};代理相關(guān)配置可以以字符串的方式先存儲在數(shù)據(jù)庫中,再根據(jù)需要讀取和修改以實(shí)現(xiàn)動態(tài)更新代理配置:
const { getSettingCache } = require("../db/SettingManager.ts");
const createAxiosInstance = () => {
// 獲取配置信息
const settingCache = getSettingCache();
// 判斷是否開啟代理
const proxyParams = settingCache["proxy"] ? JSON.parse(settingCache["proxy"]) : null;
// {
// proxy: '{"state":true,"host":"127.0.0.1","port":10809,"protocol":"http","username":"","password":""}',
// }
}二、圖片并發(fā)下載
此處使用 p-limit 來控制并發(fā)數(shù)量:
yarn add p-limit
創(chuàng)建一個 downloadImages.ts 文件用來處理圖片下載相關(guān)方法:
// server/utils/downloadImages.ts
const { getAxiosInstance } = require('../utils/axiosConfig.ts');
const path = require("path");
const fs = require("fs");
const downloadImagesByUrls = async (imageUrls, savePath) => {
// 為避免出現(xiàn)循環(huán)導(dǎo)入,此處使用動態(tài)導(dǎo)入
const pLimit = (await import('p-limit')).default;
// 提取 url 中的文件名 例:xxx.jpg
const filenames = imageUrls.map((url) => path.basename(url));
// 判斷是否存在目標(biāo)文件夾,不存在則創(chuàng)建
if (!fs.existsSync(savePath)) {
fs.mkdirSync(savePath, { recursive: true });
}
// 下載單個圖片的函數(shù)
const downloadImage = async (url, filename) => {
// 拼接文件路徑
const fullPath = path.join(savePath, filename);
try {
// 獲取 axios 實(shí)例
const axiosInstance = await getAxiosInstance();
const response = await axiosInstance({
method: "get",
url: url,
responseType: "stream",
});
const writer = await fs.createWriteStream(fullPath);
// 用Promise包裝stream完成事件
return new Promise((resolve, reject) => {
response.data.pipe(writer);
writer.on("finish", () => resolve({ filename, success: true }));
writer.on("error", (err) => reject({ filename, success: false, error: err.message }));
response.data.on("error", (err) => reject({ filename, success: false, error: err.message }));
});
} catch (error) {
return { filename, success: false, error: error.message };
}
};
// 并發(fā)控制
const limit = pLimit(5);
// 創(chuàng)建下載任務(wù)
const tasks = imageUrls.map((url, index) =>
limit(() => downloadImage(url, filenames[index]))
);
// 執(zhí)行下載任務(wù)并等待所有任務(wù)完成
const results = await Promise.all(tasks);
return results;
};
module.exports = {
downloadImagesByUrls,
};代碼說明: 該方法可直接復(fù)制使用,需要傳遞兩個參數(shù),imageUrls 參數(shù)為需要下載的圖片列表,是一個存儲了圖片下載鏈接的數(shù)組,例:['http://xxx','http://xxx'],第二個參數(shù)是 savePath ,即文件保存路徑,例:D:/Desktop,函數(shù)會提取文件名稱進(jìn)行路徑的拼接,如果路徑不存在則會自動創(chuàng)建。
三、參考資料
https://www.npmjs.com/package/p-limit
https://www.bright.cn/blog/how-tos/axios-proxy
https://www.jianshu.com/p/8021d8851775
到此這篇關(guān)于在 Node.js 中使用 axios 配置代理并實(shí)現(xiàn)圖片并發(fā)下載的文章就介紹到這了,更多相關(guān)Node.js axios 圖片并發(fā)下載內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
npm?install?-g?@vue/cli常見問題解決匯總
這篇文章主要給大家介紹了關(guān)于npm?install?-g?@vue/cli常見問題解決的相關(guān)資料,文中通過實(shí)例代碼將解決的方式介紹的非常詳細(xì),對遇到這個問題的朋友具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2022-08-08
jwt在express中token的加密解密實(shí)現(xiàn)過程
文章詳細(xì)介紹了JWT在Node.js中的生成和驗(yàn)證過程,包括設(shè)置密鑰、使用中間件進(jìn)行token驗(yàn)證等步驟,并提供了一個完整的示例代碼,感興趣的朋友跟隨小編一起看看吧2025-01-01
Node.js實(shí)現(xiàn)http請求服務(wù)與Mysql數(shù)據(jù)庫操作方法詳解
這篇文章主要介紹了Node.js實(shí)現(xiàn)http請求服務(wù)與Mysql數(shù)據(jù)庫操作方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2022-10-10
node使用require?mkdirp創(chuàng)建文件夾示例
這篇文章主要為大家介紹了node使用require?mkdirp創(chuàng)建文件夾示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08
windows8.1+iis8.5下安裝node.js開發(fā)環(huán)境
這篇文章主要介紹了windows8.1+iis8.5下安裝node.js開發(fā)環(huán)境的方法,需要的朋友可以參考下2014-12-12

