const download = require('download')
const axios = require('axios')
const fs = require('fs')
const path = require('path')
let headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36'
}
function sleep(time) {
return new Promise((reslove) => setTimeout(reslove, time))
}
async function load(data) {
await downloadFile(data)
await sleep(3000)
console.log('下载完成')
}
async function downloadFile(data) {
for (let index =0; index < data.length; index++) {
const item = data[index]
const filename = item.img.split('/').pop();// 获取图片名称 .pop() 方法用于删除并返回数组的最后一个元素。
const filePath = `${__dirname}/img`
await download(item.img, filePath, {
filename: filename,
headers,
}).then(() => {
console.log(`Download ${index} 成功`)
return
}).catch((err) => {
console.log(`Download ${index} 失败`)
return
})
}
}
const data = [
{img:'http://www.xxx.com/xxx1.jpg'},
{img:'http://www.xxx.com/xxx2.jpg'}
]
load(data);1、初始化
npm int -y
2、安装包
npm i axios download
3、运行
node index
版权声明:
本站转载作品版权归原作者及来源网站所有,原创内容作品版权归作者所有,任何内容转载、商业用途等均须联系原作者并注明来源。如果侵犯了您的权益请与我联系,我将在24小时内删除。