saveOSSAGitte.js 2.3 KB

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