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 官網文檔地址

 
        

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM