node 使用 ssh2-sftp-client 实现 FTP 的文件上传和下载功能

运行环境: 

win7; node 10.15.1

实现步骤如下

第一步:安装 ssh2-sftp-client

npm install ssh2-sftp-client
// 或者
yarn add ssh2-sftp-client

第二步:代码实现

 1 let Client = require('ssh2-sftp-client');
 2 
 3 function put(localPath, romotePath) {
 4     let sftp = new Client();
 5     sftp.connect({
 6         host: 'xx.xx.xx.xx', // 服务器 IP
 7         port: '22',
 8         username: 'xxxx',
 9         password: 'xxxxxx'
10     }).then(() => {
11         // 上传文件
12         // return sftp.fastPut(localPath, romotePath);
13         // 下载文件
14         return sftp.get(localPath, romotePath);
15     }).then((data) => {
16         // console.log(localPath + "上传完成");
17         console.log(localPath + "下载完成");
18         sftp.end();
19     }).catch((err) => {
20         console.log(err, 'catch error');
21     });
22 }
23 
24 let srcPath = 'D:\MyDisk\my-project\node\file\test-copy.txt',
25     localPath = path.join(__dirname, 'test.txt'),
26     romotePath = '/home/xx/xx/webapps/xx/test.txt';
27 
28 // 上传文件
29 // 第一个参数是需要上传的文件的本地路径;第二个参数是服务器存放的地址
30 // put(localPath, romotePath);
31 // 下载文件
32 // 第一个参数是需要下载的文件在服务器存放的地址;第二个参数是本地存放的路径
33 put(romotePath, srcPath);

注意:

1、在上传文件的时候,使用的 fastPut 方法,使用 put 方法上传文件报错。

2、ssh2-sfttp-client 官网文档地址



原文地址:https://www.cnblogs.com/landmass/p/10899983.html