Vue3项目本地打包自动上传服务器

import { Client } from "ssh2";
import SftpClient from "ssh2-sftp-client";
import { fileURLToPath } from "url";
import { dirname } from "path";

const sftp = new SftpClient();

// SSH 连接配置
const sshConfig = {
  host: "xxx",
  port: 22,
  username: "xx",
  password: "xxxx",
};

// 获取当前模块的 URL
const __filename = fileURLToPath(import.meta.url);
// 获取当前模块的目录路径
const __dirname = dirname(__filename);

const localFolderPath = `${__dirname}/../dist`; // 本地 dist 文件夹路径
const remoteFolderPath = "/home/xxx"; // 远程服务器目标文件夹路径

/* 下面的可以不用动 */
// 封装 SSH 连接函数为 Promise
const connectSSH = (sshConfig) => {
  return new Promise((resolve, reject) => {
    const conn = new Client();
    conn
      .on("ready", () => {
        resolve(conn);
      })
      .connect(sshConfig);
    conn.on("error", (err) => {
      reject(err);
    });
  });
};

// 封装连接 SSH 并执行命令的函数为 Promise
const executeSSHCommand = (conn, command) => {
  return new Promise((resolve, reject) => {
    conn.exec(command, (err, stream) => {
      if (err) {
        conn.end();
        reject(err);
        return;
      }
      let stdout = "";
      let stderr = "";
      stream.on("data", (data) => (stdout += data.toString()));
      stream.stderr.on("data", (data) => (stderr += data.toString()));
      stream.on("close", (code, signal) => {
        // conn.end();
        if (code === 0) {
          resolve(stdout);
        } else {
          reject(stderr || `Command failed with code ${code}`);
        }
      });
    });
  });
};

// 封装上传文件夹函数为 Promise
const uploadFolder = async (localFolderPath, remoteFolderPath) => {
  await sftp
    .connect(sshConfig)
    .then(() => {
      console.log("正在上传中...");
      return sftp.uploadDir(localFolderPath, remoteFolderPath);
    })
    .then(() => {
      console.log("File uploaded successfully");
      sftp.end();
    })
    .catch((err) => {
      console.error(err.message);
      sftp.end();
    });
};

// 主函数
const main = async () => {
  try {
    // 连接 SSH
    const conn = await connectSSH(sshConfig);
    console.log("SSH 连接已建立");

    // 删除远程文件夹
    await executeSSHCommand(conn, `rm -rf ${remoteFolderPath}/*`);

    // 上传文件夹
    await uploadFolder(localFolderPath, remoteFolderPath);

    // 关闭 SSH 连接
    conn.end();
  } catch (err) {
    console.error("发生错误:", err);
    conn.end();
  }
};

// 执行主函数
main();

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容