saveOSSAGitte.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. const client = require("ssh2-sftp-client");
  2. const path = require("path");
  3. const fs = require("fs");
  4. const { execSync } = require("child_process");
  5. (async function Init() {
  6. const localDir = "dist/";
  7. const dirPath = path.resolve(__dirname, "./" + localDir);
  8. const list = [];
  9. /**
  10. * 获取localDir下的所有文件路径
  11. * @param {string} pathDir
  12. */
  13. async function getFiles(pathDir) {
  14. const dirList = fs.readdirSync(pathDir) || [];
  15. for (let i = 0; i < dirList.length; i++) {
  16. const P = [pathDir, dirList[i]];
  17. const stat = fs.lstatSync(P.join("\\"));
  18. if (!stat.isDirectory()) {
  19. list.push(P);
  20. } else getFiles(P.join("\\"));
  21. }
  22. }
  23. async function upServer() {
  24. const config = {
  25. path: {
  26. // 远程地址
  27. romotePath: "/var/www/test",
  28. // 本地地址
  29. localPath: path.resolve(__dirname, "./dist"),
  30. },
  31. romote: {
  32. // 服务器 ip 地址
  33. host: "123.57.195.226",
  34. // 端口号,默认是 22
  35. port: 22,
  36. // 登录的用户名
  37. username: "root",
  38. // 登录密码
  39. password: "581100Li.",
  40. },
  41. };
  42. const sftp = new client();
  43. try {
  44. await sftp.connect(config.romote);
  45. const romotePath = config.path.romotePath;
  46. const isCss = sftp.exists(romotePath + "/css");
  47. const isFonts = sftp.exists(romotePath + "/fonts");
  48. const isJs = sftp.exists(romotePath + "/js");
  49. const isIndexHtml = sftp.exists(romotePath + "/index.html");
  50. console.log("css ---> ",isCss)
  51. isCss && await sftp.rmdir(romotePath + "/css", true);
  52. isFonts && await sftp.rmdir(romotePath + "/fonts", true);
  53. isJs && await sftp.rmdir(romotePath + "/js", true);
  54. isIndexHtml && await sftp.delete(romotePath + "/index.html", true);
  55. console.log("已清空原有文件");
  56. await sftp.uploadDir(config.path.localPath, romotePath);
  57. console.log("上传完成");
  58. // 断开连接
  59. sftp.end();
  60. console.log("断开链接");
  61. } catch (err) {
  62. console.log("更新失败", err);
  63. }
  64. }
  65. /**
  66. * 上传git
  67. */
  68. function execFun() {
  69. try {
  70. execSync("git add .");
  71. execSync('git commit -m "提交"');
  72. execSync("git push");
  73. console.log("上传git---完成");
  74. } catch (e) {
  75. console.log("上传git---失败");
  76. console.error(e);
  77. }
  78. }
  79. try {
  80. execFun();
  81. await getFiles(dirPath);
  82. console.log("获取文件路径---完成");
  83. await upServer();
  84. } catch (err) {
  85. console.log("数据上传oss---失败");
  86. }
  87. })();