sftp上传文件的js脚本

1、首先执行 npm install 安装 ssh2-sftp-client 、 path、recursive-readdir 。 ssh2-sftp-client是请求时使用的client, path用来读取路径,recursive-readdir读取本地执行的文件夹

let Client = require('ssh2-sftp-client');

let path = require('path');

let sftp = new Client();

let recursive = require("recursive-readdir");

2、配置sftp的链接信息

let remote_path ="服务器路径";

let local_path ="本地路径";

let options = {

    host: "172.0.0.0",

    port: 22,

    username: "userName",

    password:"password"

};

3、创建sftp进行上传

try {

sftp.connect(options).then((res) => {

    // 读取文件夹

    recursive(local_path, ["*.vue", "*.gif", "*.less", ".DS_Store"], async (err,      files) => {

     new Promise(async (c, e) => {

        // 先移除sftp上数据

        let list = await sftp.list(remote_path);

        for (let i in list) {

            let data = list[i];

            if (data.type === '-') {//文件

                console.log("移除文件:",remote_path + data.name);

                await sftp.delete(remote_path + data.name);

            } else if (data.type === 'd') { //文件夹

                console.log("移除文件夹:", remote_path + data.name);

                await sftp.rmdir(remote_path + data.name, true);

            }

       }

           console.log('------------ 移除完毕 ------------');



        // 上传数据

        for (let i = 0; i < files.length; i++) {

            let file = files[i];

            let s = file.split('/');

            //注:路径这里根据自己的实际需要进行拼接            
            //  s.splice(0, 2);

            // 文件短路径

            let shortPath = '';

            for (let idx = 0; idx < s.length; idx++) {

                shortPath += `${s[idx]}${idx === s.length - 1 ? '' : '/'}`;

            }

            // 文件夹路径

            let serverP = '';

            s.forEach((sp, idx) => {

                if (idx !== s.length - 1) serverP += `${sp}/`;

            });

            // 文件夹是否存在

            let serverPath = remote_path + serverP;

            try {

                await sftp.stat(serverPath);

            } catch (e) {

                await sftp.mkdir(serverPath, true);

            }

            console.log("更新:", path.join(path.resolve(file)), "\n", remote_path + shortPath);

            sftp.put(path.join(path.resolve(file)), remote_path + shortPath);

        }



        console.log("---------------- 上传完成 --------------");

        });

    });

});

} catch (e) {

        console.log("---------------- 上传失败 --------------");

        console.log(e);

}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值