123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- const path = require("path");
- const fs = require("fs");
- const oss = require("ali-oss");
- const { execSync } = require("child_process");
- (async function Init() {
- const localDir = "dist/";
- const dirPath = path.resolve(__dirname, "./" + localDir);
- const baseOssDir = "mediaAll/";
- const client = new oss({
- region: "oss-cn-chengdu",
- // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
- accessKeyId: "LTAI4GEBqfF1GX4VwsYU2Wpg",
- accessKeySecret: "rVIv0E1lRfXOCrAmkFTZnfgWiuv4ea",
- bucket: "smcic-index",
- });
- /**
- * 获取localDir下的所有文件路径
- * @param {string} pathDir
- */
- async function getFiles(pathDir) {
- const dirList = fs.readdirSync(pathDir) || [];
- for (let i = 0; i < dirList.length; i++) {
- const P = [pathDir, dirList[i]];
- const stat = fs.lstatSync(P.join("\\"));
- if (!stat.isDirectory()) {
- await upFileOSS(P);
- } else getFiles(P.join("\\"));
- }
- }
- /**
- * 获得上传目录下的所有文件路径
- * @param {string} in_dirPath
- */
- async function delDir(in_dirPath) {
- let list = await client.list({
- prefix: in_dirPath,
- });
- (list.objects || []).splice(0, 1);
- // 删除文件
- await Promise.all(
- list.objects.map(async v => {
- try {
- await client.delete(v.name);
- } catch (error) {
- error.failObjectName = v.name;
- return error;
- }
- })
- );
- console.log("oss文件清除---完成");
- }
- /**
- * 上传文件到oss
- * @param {string} filePath
- */
- async function upFileOSS(filePath) {
- try {
- // 填写OSS文件完整路径和本地文件的完整路径。OSS文件完整路径中不能包含Bucket名称。
- // 如果本地文件的完整路径中未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件。
- let dir = filePath[0].split("\\");
- dir = dir.reverse()[0] + "/";
- if (dir === localDir) dir = "";
- await client.put(
- baseOssDir + dir + filePath[1],
- path.normalize(filePath.join("\\"))
- // 自定义headers
- //,{headers}
- );
- } catch (e) {
- console.error("未成功上传:", filePath.join("\\"));
- console.log("err--->", e);
- }
- }
- /**
- * 上传git
- */
- function execFun() {
- try {
- execSync("git add .");
- execSync(`git commit -m "${process.argv[2] || '提交'}"`);
- execSync("git push");
- console.log("上传git---完成");
- } catch (e) {
- console.log("上传git---失败");
- console.error(e);
- }
- }
- execFun();
- await delDir(baseOssDir);
- try {
- await getFiles(dirPath);
- console.log("数据上传oss---完成");
- } catch (err) {
- console.log("数据上传oss---失败");
- }
- })();
|