axios下载图片 node_nodejs axios 下载文件

用nodejs下载一张图片

分别使用流式和arraybuffer两种方式下载成功, 个人偏爱arraybuffer

流式下载

const axios = require('axios')

const fs = require('fs')

let url = 'https://gss0.baidu.com/94o3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/314e251f95cad1c83f06dc11733e6709c93d5142.jpg'

axios({

url,

responseType: 'stream'

}).then(

(resp) => {

const writer = fs.createWriteStream('./t2.jpg')

resp.data.pipe(writer)

writer.on('finish', () => {

console.log('finish')

})

writer.on('error', () => {

console.log('error')

})

}

)

arraybuffer

const axios = require('axios')

const fs = require('fs')

let url = 'https://gss0.baidu.com/94o3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/314e251f95cad1c83f06dc11733e6709c93d5142.jpg'

axios({

url,

responseType: 'arraybuffer'

}).then(

({data}) => {

fs.writeFileSync('./t.jpg', data, 'binary')

}

)

你可能感兴趣的:(axios下载图片,node)