DEV Community

Cover image for SFTP using the ssh2-sftp-client in Node JS
Abhishek Tripathi
Abhishek Tripathi

Posted on • Originally published at abhishektripathitech.blogspot.com

SFTP using the ssh2-sftp-client in Node JS

Here we will be checking on how to get the files over the sftp, As there is alot of confusion on how to fetch the files in the required format, it can be a file path or a stream or just a Buffer.

We would be using the ssh2-sftp-client library of the node js.

There are two methods for getting the file and these methods are async in nature.

**_- get(path, dst, options) ==> String|Stream|Buffer

  • fastGet(remotePath, localPath, options) ===> string_**

Let us go with the Get.
Here if we are just giving the path of the file which needs to be fetched and not providing dst and the options then the output would be in the form of buffer, so if we want to transfer this buffer as a stream to the output then We would be adding this to the Readable stream. This readable stream can be piped to the response and can be sent out. This readable stream can also be added to the zip stream and that zip stream can be piped to response, if we want to zip the files before sending, this is useful if we are fetching multiple files.

Along with the Path if we are giving the dst as the path which is the local path where the data needs to be saved into, then it automatically adds the data to the file. it doesnt give any call back if the dst is provided.
if we are giving a stream for dst then it has to be a writestream and then that writestream can be piped to readstream and again here we can pipe it to response.

If we are fetching only one file then we can directly pass in the response and the data is directly giving into response

The fastget is useful when we are downloading single file and upon that we want to save it directly then we can just give the path.

This is some basic details on the get. As many a times we tend to send the stream as response and saving of the file happens at different place and the fetching happens at another place so the local path is not aware, so for this purpose an stream has to be created without the file, for that purpose we would be passing in the buffer.

This is my first technical post. Do let me know any suggestions if any.

Top comments (0)