发布dist文件夹到OSS

默认文件1615783822754.png

分享一段将编译后的前端dist文件夹上传到阿里OSS

IT200为您导航

1. 安装ali-oss后导入相关依赖

/**
* npm install ali-oss --save
*/
const path = require("path");
const fs = require("fs");
const OSS = require("ali-oss");

2. 创建oss客户端

const client = new OSS({
bucket: "",
region: "",
accessKeyId: "",
accessKeySecret: ""
});

3. 遍历获取dist文件夹中所有文件的路径

const rootPath = path.resolve(__dirname, "./dist");
let filepaths = [];
let putCount = 0;
function readFileSync(filepath) {
let files = fs.readdirSync(filepath);
files.forEach(filename => {
let p = path.join(filepath, filename);
let stats = fs.statSync(p);
if (stats.isFile()) {
filepaths.push(p);
} else if (stats.isDirectory()) {
readFileSync(p);
}
});
}

4. 将文件路径添加到oss客户端

function put(filepath) {
const p = filepath.replace(rootPath, "").substr(1);
return client.put(p.replace("\\", "/"), filepath);
}

5. 执行上传消费OSS客户端中的任务

async function update() {
try {
// 递归获取所有待上传文件路径
readFileSync(rootPath);
let retAll = await filepaths.map(filepath => {
putCount++;
console.log(`任务添加: ${path.basename(filepath)}`);
return put(filepath);
});
Promise.all(retAll).then(res => {
const resAll = res.map(r => {
return r.res.statusCode === 200;
});
if (Object.keys(resAll).length === putCount) {
console.log("发布成功");
}
});
} catch (e) {
console.log(e);
}
}

6. 运行

// 执行上传
update();
posted @   前端小鑫同学  阅读(29)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示