saveOSSAGitte.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 isCss = sftp.exists(config.path.romotePath + "/css");
  46. const isFonts = sftp.exists(config.path.romotePath + "/fonts");
  47. const isJs = sftp.exists(config.path.romotePath + "/js");
  48. const isIndexHtml = sftp.exists(config.path.romotePath + "/index.html");
  49. isCss && await sftp.rmdir(config.path.romotePath + "/css", true);
  50. isFonts && await sftp.rmdir(config.path.romotePath + "/fonts", true);
  51. isJs && await sftp.rmdir(config.path.romotePath + "/js", true);
  52. isIndexHtml && await sftp.delete(config.path.romotePath + "/index.html", true);
  53. console.log("已清空原有文件");
  54. await sftp.uploadDir(config.path.localPath, config.path.romotePath);
  55. console.log("上传完成");
  56. // 断开连接
  57. sftp.end();
  58. console.log("断开链接");
  59. } catch (err) {
  60. console.log("更新失败", err);
  61. }
  62. }
  63. /**
  64. * 上传git
  65. */
  66. function execFun() {
  67. try {
  68. execSync("git add .");
  69. execSync('git commit -m "提交"');
  70. execSync("git push");
  71. console.log("上传git---完成");
  72. } catch (e) {
  73. console.log("上传git---失败");
  74. console.error(e);
  75. }
  76. }
  77. try {
  78. execFun();
  79. await getFiles(dirPath);
  80. console.log("获取文件路径---完成");
  81. await upServer();
  82. } catch (err) {
  83. console.log("数据上传oss---失败");
  84. }
  85. })();