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)
    }
  )
}
相关推荐
设计源3 天前
尝试通过DeepSeek来优化提高WordPress网站的打开速度,还真有效!
wordpress·deepseek
weixin_4530663710 天前
使用阿里云创建公司官网(使用wordpress)
阿里云·wordpress
podoor10 天前
四大wordpress模板站
wordpress
podoor13 天前
快速搭建WordPress网站的主题
wordpress
podoor17 天前
WP最主题专业的wordpress主题开发
wordpress
fendouweiqian19 天前
迁移WordPress网站(大文件版本)
wordpress
fendouweiqian19 天前
wordpress 利用 All-in-One WP Migration全站转移
wordpress
wordpress主题下载1 个月前
精选10个好用的WordPress免费主题
wordpress·wordpress模板·wordpress主题下载
wodrpress资源分享1 个月前
2025最新3个wordpress好用的主题
wordpress
清@尘1 个月前
ripro 主题激活 问题写入授权Token失败,可能无文件写入权限
主题·wordpress