USharing
开放博客

Node async 本地批量下载图片

let fs = require('fs')
let request = require('request')
let path = require('path')
let md5 = require('md5')


const content_tag = []

const downloadImage = (src, dest, callback) => {
  request.head(src, (err, res, body) => {
    if (err) { console.log(err); return }
    src && request(src).pipe(fs.createWriteStream(dest)).on('close', () => {
      callback && callback(null, dest)
    })
  })
}

const async = require('async')
let imageLinks = [{ title: '这才是未来大屏该有的样子', url: 'https://article-fd.zol-img.com.cn/t_s640x2000/g1/M03/02/02/ChMljl2ENKuIV553AAKEYP9wZOQAAP23wGEctEAAoR4006.jpg' }, { title: '智慧屏', url: 'https://article-fd.zol-img.com.cn/t_s640x2000/g1/M05/01/06/ChMljV1_QwqIEEeTACmpHidBeUkAAPz4QMudwgAKak2877.jpg' }]

const getSuffix = str => str.slice(str.lastIndexOf('.'))
async.mapSeries(imageLinks, function (item, callback) {
  setTimeout(function () { 
    //var destImage = path.resolve("./images/", `${item.title}${getSuffix(item.url)}`);
    let destImage = path.resolve("./images/", `${md5(item.title)}${getSuffix(item.url)}`);

    content_tag.push({
      origin_name: item.title,
      origin_url: item.url,
      md5_url: destImage
    });
    console.log(content_tag)

    downloadImage(item, destImage, (err, data) => { err ? console.log(err) : console.log(path.resolve(data)) })
    //callback && callback(null, item)
    callback(null, item)

  }, 100)

})

 

赞(0) 打赏
未经允许不得转载:USharing » Node async 本地批量下载图片

觉得文章有用就打赏一下文章作者

微信扫一扫打赏