Nodejs搭配axios下载图片

新建一个文件夹,npm i axios

实测发现只需保留node_modules文件夹,删除package.json不影响使用

1.纯下载图片

其实该方法不仅可以下载图片,其他的文件都可以下载

复制代码
const axios = require('axios')
const fs = require('fs')
var arrPic = ['https://tva1.sinaimg.cn/large/9ed5c127gy1gxbaj7wmu0j20j00g9tc3.jpg', 'https://tva1.sinaimg.cn/large/9ed5c127gy1gxbaf5rt0hj20ht0g60us.jpg']
arrPic.forEach((v, k) => {
  if (v == '') {
    console.log('======1111空文件地址')
    return
  }
  var arr = v.split('/')
  var fileName = arr.pop()
  fetchPic(v, fileName)
})

function fetchPic(picUrl, fileName) {
  axios({
    method: 'get',
    url: picUrl,
    responseType: 'arraybuffer',
  }).then(
    function (response) {
      fs.writeFileSync(fileName, response.data)
    },
    (e) => {
      console.log('错误', e)
    }
  )
}

从html文件中获取图片地址

替换部分图片地址并生成新文件及下载

用于wordpress文章正文里面的外链图片的替换

复制代码
let fs = require('fs')
const axios = require('axios')

/*
 * 下面3行是把图片地址前半段进行正则替换,并写入新的文件内
 */
var htmlStr = fs.readFileSync('./post.html', 'utf8')
var lastData = htmlStr.replace(/https:\/\/tva1.sinaimg.cn\/large\//g, 'https://pic.xxx.com/')
fs.writeFileSync('./after.html', lastData)




// 定义正则表达式来匹配图片地址
//var regex = /<img[^>]+src\s*=\s*['"]([^'"]+)['"][^>]*>/g;
var regex = /https?:\/\/tva1\S+\.(?:jpg|jpeg|png|gif)/g;
//arrPic = htmlStr.match(/https:\/\/tva1.+(\.jpg|\.jpeg|\.png|\.gif)/)
var matches = [];
var match;
while ((match = regex.exec(htmlStr)) !== null) {
  matches.push(match[0]);
}

// 输出匹配到的所有图片地址

matches.forEach((v, k) => {
  if (v == '') {
    console.log('======空文件地址')
    return
  }
  var arr = v.split('/')
  var fileName = arr.pop()
  getPic(v, fileName)
})

function getPic(picUrl, fileName) {
  axios({
    method: 'get',
    url: picUrl,
    responseType: 'arraybuffer',
  }).then(
    function (response) {
      fs.writeFileSync(fileName, response.data)
      //  response.data.pipe('c:\\user\\aexx\\Desktop' + fs.createWriteStream(fileName))
    },
    (e) => {
      console.log('错误', e.response.status)
    }
  )
}
相关推荐
gpldock22213 小时前
Flutter App Templates Deconstructed: A 2025 Architectural Review
开发语言·javascript·flutter·wordpress
Junson1420992 天前
使用雷池Waf架构搭建woocommerce外贸网站
wordpress·waf·雷池·woocommerce
Web极客码2 天前
WordPress 在哪里存储网站上的图片?
运维·服务器·wordpress
2601_949532843 天前
Psello HTML Template: A Developer‘s Deep-Dive Review and Guide - Download Free
前端·windows·html·seo·wordpress·gpl
Web极客码3 天前
选择CDN提升WordPress博客速度
cdn·wordpress·网站加速
探索宇宙真理.6 天前
AhaChat Messenger WordPress漏洞 | CVE-2025-14316 复现&研究
经验分享·开源·wordpress·安全漏洞
WordPress学习笔记8 天前
WordPress主题模板与插件定制
wordpress
WordPress学习笔记9 天前
利用Multisite实现WordPress多语言网站
wordpress
Web极客码10 天前
如何在WooCommerce中隐藏产品价格
wordpress·网站优化·woocommerce
gpldock22210 天前
Medicon Theme Review: A Deep Dive for Developers and Clinic Owners - Free
wordpress