By the time you are through with this post, we hope we’ve done our job by familiarizing you with writing Node.js code to ultimately be able to connect and interact with SFTP servers. SFTP is a commonly used standard, and secure protocol that focuses on safe file and data transfer. When setting up a connection with the server, there are a few steps required to complete; let's begin!
Requirements
First things first: preparation. ssh2-sftp-client is an SFTP client for node.js, which serves as a wrapper around SSH2 to provide a high level abstraction for SFTP- related functionality. Once you are ready to install it, begin by manually running the following code:
npm install ssh2-sftp-client@^8.0.0
Or add a package.json file and declare your dependencies in it:
As an example for this post, we’ll be using an environment variable named SFTPTOGO_URL, which contains all of the information required to connect to an SFTP server in a URI format: sftp://user:password@host. The variable is parsed to extract the URI parts using URI.parse, and the remote server’s host key is verified by default using ~/.ssh/known_hosts.
Listing Files
Once a working connection has been established, you may use it to list files on the remote SFTP server. This can be done by calling the ssh2-sftp-client’s list method and iterating over the returned array, which then corresponds to the files found in the path argument. In our example, our wrapper function simply prints out the files found in the remote path.
Upload File
The next step is to upload a file. Use the client object’s put function and pass the path to the local file and the remote path ( the file should also end up here after the upload). A function call would look like this: await client.uploadFile("./local.txt", "./remote.txt");
Download File
To finalize the process, you just need to download the files. Use the client object get function and pass the path to the remote file and the local path in which to store the downloaded file. You would call the function like so: await client.downloadFile("./remote.txt", "./download.txt");
The Whole Thing
After following the above steps, the process is complete! Lastly, if you would like to run the entire program from start to finish, copy the following code and save it as main.js:
Finally, run it using the command:
node main.js
Congratulations on connecting to SFTP using Node.js!