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 = /]+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)
    }
  )
}





你可能感兴趣的:(wordpress)