前端node.js 自动打包上传到sftp 并通知钉钉机器人

  • Post author:
  • Post category:其他




sftp上传

const path = require('path')
const axios = require('axios');
const package=require('./package.json')
const shell = require("shelljs");




if (shell.exec("yarn build").code !== 0) {
    // 执行npm run build 命令
    shell.echo("Error: get coding failed");
    shell.exit(1);
}


// 钉钉机器人请求地址
const apiUrl='https://oapi.dingtalk.com/robot/send?access_token=***'
const param={
    "msgtype": "link",
    "link": {
        "title": "",
        "text": ``,
        "messageUrl": ""
    }
}
const data = JSON.stringify(param)

const webHookConfig = {
    method: 'post',
    url: apiUrl,
    headers: {
        'Content-Type': 'application/json'
    },
    data : data
};




const Client = require('ssh2-sftp-client');
const sftp = new Client();

const config = {
    host: '',
    port: '22',
    username: '',
    password: ''
}
/**
 * 上传文件到sftp
 * @param { Object } config    sftp 链接配置参数
 * @param { String } config.host sftp 主机地址
 * @param { String } config.port sftp 端口号
 * @param { String } config.username sftp 用户名
 * @param { String } config.password sftp 密码
 *
 * @param { Object } options 配置参数
 * @param { String } localStatic // 本地静态资源文件夹路径
 * @param { String } remoteStatic // 服务器静态资源文件夹路径
 * @param { String } localFile // 本地html页面
 * @param { String } remoteFile // 服务器html页面
 */
function upload(config, options) {
    sftp.connect(config)
        .then(() => {
            console.log('sftp链接成功')
            console.log('文件上传中');
            return sftp.uploadDir(options.localStatic, options.remoteStatic);
        }).then((data) => {
            console.log('文件上传成功');
            axios(webHookConfig)
                .then(function (response) {
                    console.log(JSON.stringify(response.data));
                })
                .catch(function (error) {
                    console.log(error);
                });
            sftp.end();
    }).catch((err) => {
        console.log('上传失败', err);
        sftp.end();
    })
}

// 上传文件
upload(config, {
    localStatic: path.resolve(__dirname, './.vitepress/dist'), // 本地文件夹路径
    remoteStatic: '/', // 服务器文件夹路径器
})



ftp上传

const options = {
    host: "",
    port: "21",
    user: "",
    password: ""
    // proxy:{
    //   host: '',
    //   port: '',
    // }
};

const FtpDeploy = require("ftp-deploy");


const ftpDeploy = new FtpDeploy();

const config = {
    ...options,
    // localRoot: path.resolve(__dirname,'../zip'),
    // include: ["dist.zip"], // this would upload everything except dot files
    localRoot: path.resolve(__dirname,'./.vitepress/dist'),
    include: ["*", "**/*"], // this would upload everything except dot files
    remoteRoot: "/",
    // include: ["*.php", "dist/*", ".*"],
    // e.g. exclude sourcemaps, and ALL files in node_modules (including dot files)
    // exclude: ["dist/**/*.map", "node_modules/**", "node_modules/**/.*", ".git/**"],
    exclude: [],
    // delete ALL existing files at destination before uploading, if true
    deleteRemote: false,
    // Passive mode is forced (EPSV command is not sent)
    forcePasv: false
};


// use with callback
ftpDeploy.deploy(config, (err, res) => {
    if (err) {
        console.log(err);
    } else {
        console.log("finished:", res);
        axios(webHookConfig)
          .then(function (response) {
              console.log(JSON.stringify(response.data));
          })
          .catch(function (error) {
              console.log(error);
          });
    }
});

ftpDeploy.on("uploading", data => {
    console.log(`start up ${data.filename} ,fileSize ${data.totalFilesCount}`); // partial path with filename being uploaded
});
ftpDeploy.on("uploaded", data => {
    console.log("\033[33m " + data.filename + " upload done \033[39m"); // same data as uploading event
});
ftpDeploy.on("log", data => {
    console.log(data); // same data as uploading event
});
ftpDeploy.on("upload-error", data => {
    console.log(data.err); // data will also include filename, relativePath, and other goodies
});