UNPKG

@betterwood/ali-oss

Version:

ALI-OSS UPLOAD TOOLS

109 lines (102 loc) 3.55 kB
#!/usr/bin/env node 'use strict'; var minimist = require('minimist'); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var minimist__default = /*#__PURE__*/_interopDefaultLegacy(minimist); const OSS = require('ali-oss'); const glob = require('glob'); const path$1 = require('path'); let uid = 0; async function run(config) { const client = new OSS(config.oss); // 并行启动任务 console.log(`start: 任务总数:${config.task.length}`); const results = await Promise.all(config.task.map((task) => { return runTask(client, task.source, task.publicPath); })); // 计算文件总数 let total = 0; results.forEach((v) => { total = total + v; }); console.log(`√ 总数: ${total}`); console.timeEnd('√ 耗时'); } async function runTask(client, from, to) { // 转换成绝对路径 if (!path$1.isAbsolute(from)) { from = path$1.resolve(__dirname, from); } // 获取文件列表 const files = glob.sync(path$1.resolve(from, './**/*.*')); // 上传到oss await upload(files, from, to, client); console.log(`${++uid}、 Done: { Total:${files.length}, From:'${from}', To:'${to}' }`); return files.length; } async function upload(files, from, to, client) { return Promise.all(files.map((file) => { // 目标地址 const targetPath = path$1.posix.normalize(file.replace(from.replace(/\\/g, '/'), to).replace(/\\/g, '/')); // 调用oss put接口上传 return client .put(targetPath, file) .then((res) => { if (res.res.statusCode === 200) { return res; } else { console.error(res); throw res; } }) .catch((e) => { console.error(e); console.log(''); console.error(`❌❌❌ 上传失败`); process.exit(-1); }); })); } const path = require('path'); // 获取控制台参数 { _: [], config: 'alioss.config.js', id: 'a', secret: 'b' } const args = minimist__default['default'](process.argv.slice(2)); async function main() { console.time('√ 耗时'); console.log(`use config:${args.config || 'alioss.config.js'}`); // 获取配置文件 const config = require(path.resolve(process.env.PWD || process.env.INIT_CWD, args.config || 'alioss.config.js')); if (!config.oss) { console.error('x 配置缺少oss项'); process.exit(-1); } // 合并配置 const conf = { region: args.region || args.r || config.oss.region, accessKeyId: args.accessKeyId || args.i || config.oss.accessKeyId, accessKeySecret: args.accessKeySecret || config.oss.accessKeySecret, bucket: args.bucket || args.b || config.oss.bucket, }; config.oss = conf; console.log(`To Bucket: '${conf.bucket}'`); // 校验配置 if (!validate(config)) { process.exit(-1); } // 运行 run(config); } main(); function validate(config) { const { oss } = config; if (!oss.bucket || !oss.region || !oss.accessKeyId || !oss.accessKeySecret) { console.error('x oss配置不正确'); return false; } if (!config.task || !config.task.length) { console.error('x 没有配置task项'); return false; } return true; }