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)
    }
  )
}
相关推荐
豆豆4 天前
2026 主流 CMS 建站系统对比分析:企业、个人建站该如何选型?
wordpress·建站系统·cms建站·企业建站·建站选型·saas建站·2026建站指南
VIP_CQCRE6 天前
用 Ace Data Cloud 自动发布 WordPress 文章:把 AI 写作变成可积累的 SEO 内容资产
ai·api·seo·wordpress·acedatacloud
VIP_CQCRE13 天前
用 Ace Data Cloud 自动发布 WordPress 文章:把 SEO 内容站变成长期增长资产
ai·自动化·seo·wordpress·acedatacloud
2601_9657984717 天前
Renovate Theme Setup: Fast Contractor & Construction Site Architecture
theme·wordpress
2601_9657984718 天前
Salient Theme Setup Guide for Fast Creative WordPress Sites
数据库·web3·php·wordpress
2601_9657984721 天前
Boutique Business Consulting WordPress Architecture & SEO Setup
android·theme·wordpress
2601_9657984722 天前
Plastic Surgery Clinic Web Setup: Deploying Rejuvita WordPress
php·theme·wordpress
2601_9657984722 天前
Contractor Web Setup: Deploying Bathrooms & Kitchens Theme Fast
前端·web3·php·wordpress
e6zzseo1 个月前
wordpress独立站seo怎么做才有效
seo·wordpress·独立站·内容优化·外链建设
Web极客码1 个月前
如何让用户订阅WordPress评论?提升用户互动的有效策略
运维·服务器·wordpress