如何在 Node.js 中使用 axios 配置代理并實(shí)現(xiàn)圖片并發(fā)下載
一、創(chuàng)建 Axios 實(shí)例
可以創(chuàng)建一個(gè) 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)配置可以以字符串的方式先存儲(chǔ)在數(shù)據(jù)庫中,再根據(jù)需要讀取和修改以實(shí)現(xiàn)動(dòng)態(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)建一個(gè) 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)入,此處使用動(dòng)態(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 }); } // 下載單個(gè)圖片的函數(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ù)制使用,需要傳遞兩個(gè)參數(shù),imageUrls
參數(shù)為需要下載的圖片列表,是一個(gè)存儲(chǔ)了圖片下載鏈接的數(shù)組,例:['http://xxx','http://xxx']
,第二個(gè)參數(shù)是 savePath
,即文件保存路徑,例:D:/Desktop
,函數(shù)會(huì)提取文件名稱進(jìn)行路徑的拼接,如果路徑不存在則會(huì)自動(dòng)創(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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于Alpine Linux構(gòu)建前端node-web鏡像步驟詳解
這篇文章主要為大家介紹了基于Alpine Linux構(gòu)建前端node-web鏡像步驟詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11在Node.js中發(fā)出HTTP請(qǐng)求的 5 種方法
學(xué)習(xí)如何在 Node.js 中發(fā)出 HTTP 請(qǐng)求可能會(huì)讓人感到不知所措,因?yàn)橛袛?shù)十個(gè)可用的庫,每個(gè)解決方案都聲稱比上一個(gè)更高效,在這篇文章中,我們將探討在 Node.js 中發(fā)出 HTTP 請(qǐng)求的五種最流行的方法,并為每種方法提供說明,需要的朋友可以參考下2023-11-11Node解決簡(jiǎn)單重復(fù)問題系列之Excel內(nèi)容的獲取
這篇文章主要給大家介紹了關(guān)于利用Node解決簡(jiǎn)單重復(fù)問題系列之Excel內(nèi)容獲取的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧。2018-01-01詳解Wondows下Node.js使用MongoDB的環(huán)境配置
這篇文章主要介紹了詳解Wondows下Node.js使用MongoDB的環(huán)境配置,這里使用到了Mongoose驅(qū)動(dòng)來讓JavaScript操作MongoDB,需要的朋友可以參考下2016-03-03Nodejs實(shí)現(xiàn)圖片上傳、壓縮預(yù)覽、定時(shí)刪除功能
本文分步驟給大家介紹了Nodejs實(shí)現(xiàn)圖片的上傳、壓縮預(yù)覽、定時(shí)刪除功能,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-10-10