Node uses SSH2 SFTP Client to upload and download FTP files

Operating environment.

win7; node 10.15.1

The implementation steps are as follows

Step 1: Installation ssh2-sftp-client

npm install ssh2-sftp-client
// or
yarn add ssh2-sftp-client

Step 2: code implementation

 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', // Servers IP
 7         port: '22',
 8         username: 'xxxx',
 9         password: 'xxxxxx'
10     }).then(() => {
11         // upload
12         // return sftp.fastPut(localPath, romotePath);
13         // Download
14         return sftp.get(localPath, romotePath);
15     }).then((data) => {
16         // console.log(localPath + "Uploaded");
17         console.log(localPath + "Downloaded");
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 // Upload file
29 // The first parameter is the local path of the file to be uploaded; the second parameter is the address where the server is stored
30 // put(localPath, romotePath);
31 // Download the file
32 // The first parameter is the address of the server where the file to be downloaded is stored; the second parameter is the local path
33 put(romotePath, srcPath);

note:

1. When uploading files, the fastput method is used, and the put method is used to upload files and report errors

2. SSH2 sfttp client official website document address

Similar Posts: