saveOSSAGitte.js 2.8 KB

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