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);
}