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();