saveOSSAGitte.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. // const client = require("ali-oss");
  2. const path = require("path");
  3. const fs = require("fs");
  4. const oss = require("ali-oss");
  5. const { execSync } = require("child_process");
  6. (async function Init() {
  7. const localDir = "dist/";
  8. const dirPath = path.resolve(__dirname, "./" + localDir);
  9. const baseOssDir = "zhoubao/view/";
  10. const client = new oss({
  11. region: "oss-cn-chengdu",
  12. // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
  13. accessKeyId: "LTAI4GEBqfF1GX4VwsYU2Wpg",
  14. accessKeySecret: "rVIv0E1lRfXOCrAmkFTZnfgWiuv4ea",
  15. bucket: "smcic-index",
  16. });
  17. /**
  18. * 获取localDir下的所有文件路径
  19. * @param {string} pathDir
  20. */
  21. async function getFiles(pathDir) {
  22. const dirList = fs.readdirSync(pathDir) || [];
  23. for (let i = 0; i < dirList.length; i++) {
  24. const P = [pathDir, dirList[i]];
  25. const stat = fs.lstatSync(P.join("\\"));
  26. if (!stat.isDirectory()) {
  27. await upFileOSS(P);
  28. } else getFiles(P.join("\\"));
  29. }
  30. }
  31. /**
  32. * 获得上传目录下的所有文件路径
  33. * @param {string} in_dirPath
  34. */
  35. async function delDir(in_dirPath) {
  36. let list = await client.list({
  37. prefix: in_dirPath,
  38. });
  39. (list.objects || []).splice(0, 1);
  40. // 删除文件
  41. await Promise.all(
  42. list.objects.map(async v => {
  43. try {
  44. await client.delete(v.name);
  45. } catch (error) {
  46. error.failObjectName = v.name;
  47. return error;
  48. }
  49. })
  50. );
  51. console.log("oss文件清除---完成");
  52. }
  53. /**
  54. * 上传文件到oss
  55. * @param {string} filePath
  56. */
  57. async function upFileOSS(filePath) {
  58. try {
  59. // 填写OSS文件完整路径和本地文件的完整路径。OSS文件完整路径中不能包含Bucket名称。
  60. // 如果本地文件的完整路径中未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件。
  61. let dir = filePath[0].split("\\");
  62. dir = dir.reverse()[0] + "/";
  63. if (dir === localDir) dir = "";
  64. await client.put(
  65. baseOssDir + dir + filePath[1],
  66. path.normalize(filePath.join("\\"))
  67. // 自定义headers
  68. //,{headers}
  69. );
  70. } catch (e) {
  71. console.error("未成功上传:", filePath.join("\\"));
  72. console.log("err--->", e);
  73. }
  74. }
  75. /**
  76. * 上传git
  77. */
  78. function execFun() {
  79. try {
  80. execSync("git add .");
  81. execSync('git commit -m "提交"');
  82. execSync("git push");
  83. console.log("上传git---完成");
  84. } catch (e) {
  85. console.log("上传git---失败");
  86. console.error(e);
  87. }
  88. }
  89. execFun();
  90. await delDir(baseOssDir);
  91. try {
  92. await getFiles(dirPath);
  93. console.log("数据上传oss---完成");
  94. } catch (err) {
  95. console.log("数据上传oss---失败");
  96. }
  97. })();