axios结合fs实现文件下载保存

nodejs yekong 103℃

在用nodejs仿写单页模板扒手的时候,需要下载js文件,这里用到了axios以及fs来实现功能。

使用

async getDownJs() {
      var that = this;
      for (const url of that.jslist) {
        await downloadJs(url,that.downForm.dir)
      }
    },

downloadJs

import axios from 'axios'
import fs from 'fs'

export function downloadJs(u, p) {
    return axios.get(u, {
        method: 'GET',
        headers: {
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.85 Safari/537.36",
            "Referer": u,
        },
        responseType: 'buffer'
    }).then(res => {
        console.log(res)
        if (!fs.existsSync(p + "/js/")) {
            fs.mkdirSync(p + "/js/");
        }
        fs.writeFile(p + "/js/" + u.split("/").reverse()[0], res.data, "binary", function (err) {
            console.log(err || p);
        });
    });
}

喜欢 (0)