saveOSSAGitte.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // const client = require("ali-oss");
  2. const path = require("path");
  3. const fs = require("fs");
  4. const oss = require("ali-oss");
  5. (async function Init() {
  6. const localDir = "dist/";
  7. const dirPath = path.resolve(__dirname, "./" + localDir);
  8. const baseOssDir = "topic/";
  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("文件清除完成");
  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. console.log(baseOssDir + dir + filePath[1],filePath.join("\\"))
  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. await delDir(baseOssDir);
  76. await getFiles(dirPath);
  77. })();