批量下载文件脚本
This commit is contained in:
53
batch-download/index.js
Normal file
53
batch-download/index.js
Normal file
@@ -0,0 +1,53 @@
|
||||
const axios = require('axios');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
// 示例图片 URL 数组
|
||||
const imageUrls = [
|
||||
// 'https://example.com/image1.jpg',
|
||||
// 'https://example.com/image2.jpg',
|
||||
// 'https://example.com/image3.jpg',
|
||||
];
|
||||
|
||||
for (let i = 1; i <= 100; i++) {
|
||||
imageUrls.push(`https://example.com/image${i}.jpg`)
|
||||
}
|
||||
|
||||
// 执行下载
|
||||
downloadImages(imageUrls);
|
||||
|
||||
// 批量下载图片函数
|
||||
async function downloadImages(urls) {
|
||||
for (const url of urls) {
|
||||
// const imageName = path.basename(url); // 获取图片名称
|
||||
const imageName = (imageUrls.indexOf(url) + 1) + '.jpg'; // 图片名称递增
|
||||
const imagePath = path.join(__dirname, 'downloads', imageName); // 图片保存路径
|
||||
|
||||
try {
|
||||
const response = await axios({
|
||||
method: 'get',
|
||||
url: url,
|
||||
responseType: 'stream', // 让 axios 直接返回图片流
|
||||
});
|
||||
|
||||
// 确保下载目录存在
|
||||
if (!fs.existsSync(path.dirname(imagePath))) {
|
||||
fs.mkdirSync(path.dirname(imagePath), { recursive: true });
|
||||
}
|
||||
|
||||
// 将图片流写入本地文件
|
||||
const writer = fs.createWriteStream(imagePath);
|
||||
response.data.pipe(writer);
|
||||
|
||||
writer.on('finish', () => {
|
||||
console.log(`图片下载完成:${imageName}`);
|
||||
});
|
||||
|
||||
writer.on('error', (err) => {
|
||||
console.error(`下载图片失败:${imageName}`, err);
|
||||
});
|
||||
} catch (err) {
|
||||
console.error(`下载图片出错:${url}`, err);
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user