博客一键上传到阿里云OSS

起因

​ 因为之前每次写文章都要登陆阿里云,手动上传文件比较繁琐,用提供的客户端老是需要重新输入密码,记住密码可能会弄丢,所以干脆用gulp写个上传的方法,命令一执行就可以实现一键生成压缩部署。

安装依赖

只需要安装ali-oss:

1
npm install ali-oss --save-dev

用到了node自带的fs模块

开始实现上传文件

  1. 遍历目录文件,将结果保存在fileList中。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    var fs = require('fs')
    var fileList = []
    function walk(path){
    var dirList = fs.readdirSync(path);

    dirList.forEach(function(item){
    if(fs.statSync(path + '/' + item).isFile()){
    fileList.push(path + '/' + item);
    }
    });

    dirList.forEach(function(item){
    if(fs.statSync(path + '/' + item).isDirectory()){
    walk(path + '/' + item);
    }
    });
    }
  2. 创建oss对象,具体参数参照官网。

    1
    2
    3
    4
    5
    6
    7
    let OSS = require('ali-oss');
    let client = new OSS({
    region: 'XXXXX', //参数请参考官网
    accessKeyId: 'XXXXXXXXXXXXXX', //参数请参考官网
    accessKeySecret: 'XXXXXXXXXXXXXXX', //参数请参考官网
    bucket: 'XXXXXX' //参数请参考官网
    });
  3. 写同步上传函数

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    async function put(uploadfile,localfile) {
    try {
    let result = await client.put(uploadfile, localfile);
    console.log(result);
    return true;
    } catch (e) {
    console.log(e);
    }
    return false;
    }
  4. 用gulp写上传任务

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    gulp.task('upload', done=> {
    fileList = [];
    //调用文件遍历方法
    walk('./public');
    try
    {
    fileList.forEach((item,i)=> {
    let file = item.replace('./public/','');
    //调用文件上传方法
    let result = put(file,item);
    if(!result)
    {
    throw new Error('上传文件失败');
    }
    });
    }catch(e)
    {
    console.log(e);
    }

    done();
    });

评论