准备

现要利用阿里云OSS部署一个静态网页,通过本地编译生成静态网页后实现自动上传更新部署。

  1. 首先开通阿里OSS服务,然后新建一个存储桶,权限设为公共可读,地域选择香港,因为国内域名需备案。
  2. 去存储桶基础设置->静态页面设置首页为index.html;然后去传输管理->绑定域名,最后去DNS设置cname,也可以自行配置CDN加速。
  3. 然后去阿里云控制台新建一个RAM访问控制用户,记住accessKeyId和accessKeySecret,然后为该用户添加OSS权限。

本地上传代码

本地安装npm i ali-oss -D,我们要实现将本地dist目录下所有的文件原封不动的上传至OSS上,为了保持OSS文件清洁,上传前最好先清空OSS,最终代码如下。

const OSS = require("ali-oss");
const path = require("path");
var fs = require("fs");

const client = new OSS({
    region: "oss-cn-hongkong",
    accessKeyId: "xxxxxxxxxxxx",
    accessKeySecret: "xxxxxxxxxxxx",
    bucket: "xxxxxx",
});

async function list() {
    try {
        let result = await client.list();
        result = result.objects || [];
        let file_list = result.map(i => i.name);
        return file_list;
    } catch (err) {
        console.log(err);
    }
}

async function deleteMulti(filelist) {
    try {
        let result = await client.deleteMulti(filelist, {
            verbose: true,
        });
        console.log("deleted:\n", result.deleted);
    } catch (e) {
        console.log(e);
    }
}

async function put(filename) {
    try {
        let result = await client.put(
            filename.slice(5).replace(/\\/g, "/"),
            path.normalize(filename)
        );
        console.log("upload: ", result.name);
    } catch (e) {
        console.log(e);
    }
}
function getAllfiles(dir, filelist) {
    let files = fs.readdirSync(dir);
    files.forEach(file => {
        let filepath = path.join(dir, file);
        let stat = fs.statSync(filepath);
        if (stat.isFile()) filelist.push(filepath);
        if (stat.isDirectory()) {
            filelist = filelist.concat(getAllfiles(filepath, []));
        }
    });
    return filelist;
}
async function main() {
    const file_list = await list();
    console.log("quire result:\n", file_list);
    if (file_list.length > 0) {
        await deleteMulti(file_list);
    }
    let files = getAllfiles("./dist", []);
    files.forEach(file => {
        put(file);
    });
}
main();

运行结果

参考

https://help.aliyun.com/document_detail/32068.html?spm=a2c4g.11186623.6.1058.42b92a220SHC2F
https://help.aliyun.com/document_detail/39630.html?spm=a2c4g.11186623.6.666.1b263331Q5jiQY

最后修改:2021 年 05 月 30 日 03 : 29 PM