引言

作为一个web前端开发,对axios肯定不陌生,但是在前端开发中,一般是使用axios来请求后端接口,获取数据。而使用node+axios下载网络文件到本地磁盘可能很少接触,搜索了很多相关的博客文章,讲解的好像都不够清晰明了,所以本文就记录一下实践方法。

初始化项目

npm init -y

安装axios

 npm i -s axios

实现逻辑

根目录下新建app.js

// app.js
const axios = require('axios');
const fs = require('fs');

async function loadimg(imgurl) {
  let { data } = await axios({
    url: imgurl,
    headers: {
      'content-type': 'multipart/form-data',
    },
    responsetype: 'arraybuffer',
  })
  await fs.promises.writefile(`./01.jpg`, data, 'binary');
}

;(async function () {
  let url = 'https://tiven.cn/static/img/img-post-08-c1kr9hq13ltemcyi_mowx.jpg'
  console.time('download time:')
  try {
    await loadimg(url)
    console.log('下载成功')
  } catch (err) {
    console.log(err)
  }
  console.log('')
  console.timeend('download time:')
})();

说明:

axios 的参数 headers 中 content-type默认是application/json,需要设置为 multipart/form-data

responsetype默认是json,需要设置为arraybuffer(二进制格式);

writefile方法的第三个参数encoding默认是utf8,必须设置为binary(二进制格式),如果不设置,下载的文件打不开。

console.timeconsole.timeend是node中提供的计时方法。

执行

node app.js

输出

下载成功
download time:107.866ms

如果想要批量爬取某个网站的图片或其他文件,可以使用node爬虫工具cheerio来实现。

参考文档

http://nodejs.cn/api/fs.html#fs_fs_writefile_file_data_options_callback

http://www.axios-js.com/docs/#request-config

以上就是node+axios实现下载外网文件到本地的详细内容,更多关于node axios下载外网文件到本地的资料请关注其它相关文章!