ssh2-sftp-client实现前端项目自动部署

目录

自动部署完整代码 

package.json

 deploy /config   服务器信息

 deploy / index  部署命令入口文件

 如果需要在服务器执行命令

shelljs的使用说明

shelljs的安装

shelljs的使用说明

重要方法介绍

exec()

 ls()

ShellString()

ShellString.prototype.to(file)

ShellString.prototype.toEnd(file)

SSH2-SFTP-Client 使用文档

安装

使用方法

new SftpClient(name) ===> SFTP client object

connect(config) ===> SFTP object 

downloadDir(srcDir, dstDir, options) ==> string

rmdir(path, recursive) ==> string 

uploadDir(srcDir, dstDir, options) ==> string 

node js --- fs模块

.mkdir 创建文件夹 

 __dirname

path.resolve()用法 

process

1. 了解process.argv

 2. process对象的用途

3. 结论

chalk开源库

前言

chalk作用与使用

chalk在node中使用的版本坑

chalk在node中使用场景


自动部署完整代码 

package.json

下载这三个包

  • shelljs :执行 shell命令
  • ssh2-sftp-client 与服务器建立链接(内部有ssh2)
  • chalk 打印彩色输出
  "devDependencies": {
    "shelljs": "^0.8.5",
    "ssh2-sftp-client": "^9.1.0",
    "chalk": "4.1.0"
  },

配置脚本命令  deploy 注意后边加上运行环境
执行deploy命令时内部执行了打包动作

  "scripts": {
    "dev": "vue-cli-service serve",
    "staging": "vue-cli-service serve --mode staging",
    "build:prod": "vue-cli-service build",
    "build:stage": "vue-cli-service build --mode staging",
    "preview": "node build/index.js --preview",
    "lint": "eslint --ext .js,.vue src",
    "deploy": "node deploy/index.js --prod"
  },

 deploy /config   服务器信息

module.exports = [
  {
    id: 0,
    nodeEnv: "prod",
    name: "正式环境",
    domain: "",
    host: "ip",
    port: 端口,
    username: "用户名",
    password: "密码",
    path: "/data/www/paccount",//部署路径
    removepath: "/data/www/paccount", //删除路径
  },
];

 deploy / index  部署命令入口文件

// 服务器配置文件
const config = require("./config.js");
// shell命令
const shell = require("shelljs");
// 输出颜色
const chalk = require("chalk");
// node fs 模块 读写文件
const fs = require("fs");
// node path模块 获取文件路径
const path = require("path");
// SSH2-SFTP-Client 是一个用于在Node.js中进行SSH SFTP操作的强大工具。它允许你建立SSH连接并进行文件传输,非常适用于自动化任务和远程文件管理。本文将引导你如何安装、配置和使用SSH2-SFTP-Client。
const Client = require("ssh2-sftp-client");
// 获取环境变量
const rawArgv = process.argv.slice(2);
// 日期插件
const dayjs = require("dayjs");

//判断环境
const filterStage = rawArgv.includes("--prod") ? "prod" : "stage";
console.log(chalk.blue("当前环境:", filterStage));

// 打包
const compileDist = async () => {
  // 根据环境执行打包命令
  if (shell.exec(`npm run build:${filterStage}`).code === 0) {
    console.log(chalk.green("打包成功"));
  }
};
// 部署
async function connectShell(params) {
  // 判断需要上传的服务器
  config
    .filter((item) => item.nodeEnv == filterStage)
    .map((item, index) => {
      const sftp = new Client();
      sftp
        .connect({
          host: item.host,
          port: item.port,
          username: item.username,
          password: item.password,
        })
        // 备份
        .then(() => {
          if (index > 0) {
            return "ok";
          }
          console.log(
            chalk.red(`${item.host}--`) + chalk.blue(`---执行下拉文件备份---`)
          );
          console.log(chalk.blue(`---创建备份文件夹中···---`));
          let newFile = `/${item.host}/${dayjs().format(
            "YYYY-MM-DD"
          )}/dist-${dayjs().format("HH_mm_ss")}`;
          // 创建本地文件夹
          fs.mkdir(
            path.resolve(__dirname, `../distbak${newFile}`),
            { recursive: true },
            (err) => {
              if (err) throw err;
              console.log(chalk.green("---创建备份文件夹成功---"));
            }
          );
          //执行服务器下拉操作
          return sftp.downloadDir(
            item.path, //服务器路径
            path.resolve(__dirname, `../distbak${newFile}`) //写入的本地路径地址
          );
        })
        // 删除
        .then(() => {
          if (index === 0) {
            console.log(
              chalk.red(`${item.host}--`) + chalk.blue(`---备份完成---`)
            );
          }
          console.log(
            chalk.yellow(`${item.host}--`) +
              chalk.red(`---执行删除文件中···---`)
          );
          // 删除路径 递归删除
          return sftp.rmdir(item.path, true);
        })
        // 上传
        .then(() => {
          console.log(
            chalk.red(`${item.host}--`) + chalk.green(`执行删除文件成功---`)
          );
          console.log(
            chalk.hex("#DEADED").bold(`---${item.host}执行上传文件中···---`)
          );
          return sftp.uploadDir(path.resolve(__dirname, "../dist"), item.path);
        })
        // 上传成功 关闭链接
        .then(() => {
          console.log(
            chalk.yellow(`${item.host}--`) + chalk.green(`上传完成,部署成功---`)
          );
          sftp.end();
        })
        // 上传失败
        .catch((err) => {
          console.error(
            err,
            chalk.red(`${item.host}--`) + chalk.red(`上传失败`)
          );
          sftp.end();
        });
    });
}

async function runStart() {
  await compileDist();
  await connectShell();
}
runStart();

 如果需要在服务器执行命令

在部署完成后执行

SSH2是一个用于在网络上安全地访问远程计算机的协议,而上述代码段则使用Node.js的ssh2库来执行SSH连接和操作。这段代码中包含了两个事件处理器:

  1. .on("ready", function () { ... })

    • 这是ssh2库中的一个事件处理器,它在SSH连接准备就绪时触发。当与远程主机建立SSH连接后,会执行其中的代码块。通常,你可以在这个事件中执行需要在SSH连接建立后执行的操作。
  2. .connect({ ... })

    • 这是用于建立SSH连接的方法,其中包含了一个包含连接参数的对象,如主机地址、端口、用户名和密码等。在调用.connect()时,ssh2库将尝试连接到指定的远程主机。

在代码中,当SSH连接准备就绪("ready")时,它执行了一个命令,使用conn.exec()执行chmod命令,将目标目录的权限设置为755(允许读、写和执行)。如果设置权限成功,它会打印一条成功消息,并结束SSH连接。

总之,上述代码段通过ssh2库建立SSH连接,并在连接就绪后执行特定的命令来更改目标目录的权限。这通常用于在远程服务器上执行操作,例如修改文件权限。

const ClientOrg = require("ssh2").Client;
async function chmodDir(item) {
  if (!item) {
    throw "获取ip配置失败";
  }

  const conn = new ClientOrg();
  conn
    .on("ready", function () {
      conn.exec("chmod  755  /etc/nginx/html -R", function (err, stream) {
        if (err) throw err;
        console.log(
          chalk.red(`${item.host}--`) + chalk.green(`---添加目录权限成功---`),
        );
        conn.end();
      });
    })
    .connect({
      host: item.host,
      port: item.port,
      username: item.username,
      password: item.password,
    });
}

shelljs的使用说明
 

shellj

### 使用 VSCode 部署前端资源 #### 安装必要的扩展 为了简化开发流程并提高效率,在 Visual Studio Code 中安装一些有用的插件是非常有帮助的。对于前端项目来说,推荐安装以下几种类型的扩展: - **Live Server**:该工具可以启动本地服务器来实时预览网页效果[^1]。 ```json { "liveServer.settings.port": 5500, } ``` - **Prettier - Code formatter** 和 **ESLint**:用于保持代码风格一致性和静态分析错误检测[^2]。 #### 设置工作区配置文件 创建 `.vscode` 文件夹并在其中加入 `settings.json` 来定制化编辑器行为以及集成构建脚本。这有助于自动化任务执行,比如编译 SASS 或者运行测试套件等操作[^3]。 ```json // ./.vscode/settings.json { "editor.formatOnSave": true, "files.autoSave": "afterDelay", "[javascript]": { "editor.defaultFormatter": "esbenp.prettier-vscode" } } ``` #### 构建与打包过程 通常情况下,现代 JavaScript 应用程序会依赖于像 Webpack 这样的模块捆绑器来进行优化处理。确保项目的根目录下存在合适的 webpack.config.js 文件,并且已经定义好了入口起点(entry point),出口位置(output path)等相关参数设置[^4]。 ```bash npx webpack --mode production ``` #### 发布到远程仓库或云服务提供商 完成上述准备工作之后,就可以考虑如何把最终产物上传至目标环境了。这里介绍两种常见的方式: ##### 方法一:通过 Git/GitHub Actions 自动化 CI/CD 流程 利用 GitHub 的持续集成特性可以在每次提交新版本时自动触发一系列动作,包括但不限于单元测试、安全扫描乃至直接推送更新后的静态页面给托管平台(例如 Netlify 或 Vercel)。只需编写相应的 workflow YAML 文件即可实现这一目的[^5]。 ```yaml name: Build and Deploy on: push: branches: - main jobs: build-and-deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Install dependencies & Build project run: | npm install npm run build - name: Deploy to Production Environment env: NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }} SITE_ID: my-awesome-site-id run: npx netlify-cli deploy --prod --message="Deploy from GitHub Action" ``` ##### 方法二:借助 FTP/SFTP 插件手动同步文件 如果倾向于更传统的手段,则可以选择安装 FileZilla Client 或类似的客户端软件;当然也可以寻找支持 sftp 协议传输功能的 vs code 扩展包,从而不必离开 IDE 就能轻松管理远端主机上的文档结构[^6]。 ```json // settings.json inside the workspace folder (.vscode/) { "remote.SSH.remotePlatform": {}, "sftp.remotes": [ { "host": "example.com", "username": "your_username", "password": "your_password", // Not recommended; use key-based authentication instead. "port": 22, "protocol": "sftp", "privateKeyPath": "~/.ssh/id_rsa", "passphrase": "", "interactiveAuth": false, "context": ["*"], "connectTimeout": null, "uploadOnSave": true } ] } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值