How To Upload and Download a File With FTP/FTPS/SFTP in Node.js
Tags: javascript, node, softwaredevelopment, softwareengineering
Published: 2024-01-19 21:29:17

In this article, you will learn how to deal with FTP, FTPS, and SFTP in Node.js. In detail, you will see how to upload and download a file via FTP/FTPS with `basic-ftp`, and how to do the same via SFTP with `ssh2-sftp-client`.

Let's jump into it!

## A Bit of Theory on FTP, FTPS, and SFTP

FTP ([File Transfer Protocol](https://en.wikipedia.org/wiki/File_Transfer_Protocol)), FTPS ([FTP Secure](https://en.wikipedia.org/wiki/FTPS)), and SFTP ([SSH File Transfer Protocol](https://en.wikipedia.org/wiki/SSH_File_Transfer_Protocol)) are three different protocols for transferring files over the Internet. They all serve the same purpose but differ when it comes to the security they provide.

FTP is the oldest and most basic file transfer protocol. Since it transfers files in plain text, it is no longer considered secure.

FTPS is a secure version of FTP that uses SSL or TLS to secure the data being transferred.

SFTP uses an [SSH](https://en.wikipedia.org/wiki/Secure_Shell) connection for transferring files, making it the most secure file transfer protocol of the three.

Generally, FTP client libraries allow you to connect to both FTP and FTPS. On the contrary, SFTP requires specific libraries. This is also what typically happens in Node.js.

## FTP/FTPS in Node.js

To connect to an FTP or FTPS server using Node.js, you can use [`basic-ftp`](https://www.npmjs.com/package/basic-ftp). As stated on the [official GitHub page of the project](https://github.com/patrickjuchli/basic-ftp), `basic-ftp` is an FTP client library for Node.js that supports FTP, FTPS, and Passive Mode over IPv6.

First, install `basic-ftp` with the following command:npm i basic-ftp

You can then use it to connect to an FTP or FTPS server, as in the following example:

```javascript
// import basic-ftp
const ftp = require("basic-ftp") 
// ESM: import * as ftp from "basic-ftp"

// to activate the debug mode
client.ftp.verbose = true

async function operationWithFTP() {
    // initialize the FTP client
    const client = new ftp.Client()
    
    try {
        // connect to the FTP/FTPS server
        await client.access({
            host: "<YOUR_FTP_HOST>",
            user: "<YOUR_FTP_USER>",
            password: "<YOUR_FTP_USER_PASSWORD>",
            secure: true // true for FTPS and false for FTP
        })
        
        // perform operations on the FTP server...
    } catch(e) {
        console.log(e)
    }
    
    // close the client connection
    client.close()
}
```

Be sure to replace the placeholder strings with your FTP credentials. Also, note that `basic-ftp` is a [Promise-based](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) library. For this reason, its functions should be called with the [`await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await) keyword and in an [`async`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) function. Find out more about [how to use](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Promises#async_and_await) [`Promise`](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Promises#async_and_await)[s with](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Promises#async_and_await) [`async/await`](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Promises#async_and_await) [in JavaScript](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Promises#async_and_await).

Let's learn how to upload and download a file with FTP and FTPS with `basic-ftp`!

### Download a File From FTP/FTPS server

You can create a function to download files from an FTP server withNode.js through `basic-ftp` as follows:

```javascript
const ftp = require("basic-ftp") 

async function downloadFileFromFTP(localFile, remotePath) {
    const client = new ftp.Client()
    
    try {
        await client.access({
            host: "<YOUR_FTP_HOST>",
            user: "<YOUR_FTP_USER>",
            password: "<YOUR_FTP_USER_PASSWORD>",
            secure: true
        })
        
        // download the remote file located to remotePath
        // and store it to localFile
        await client.downloadTo(localFile, remotePath)
    }
    catch(err) {
        console.log(err)
    }
    client.close()
}

// download the remote file "reports/CSV/data.csv"
// and store it to the local file "data.csv"
downloadFileFromFTP("data.csv", "reports/CSV/data.csv")
```

`downloadTo()` will download a remote file from an FTP or FTPS server and pipe its data to a writable stream or local file. In detail, `localFile` can be a [`Writable`](https://nodejs.org/api/stream.html#class-streamwritable) [Node.js stream](https://nodejs.org/api/stream.html#class-streamwritable) or a string containing the complete local path of where to store the downloaded file.

### Upload a File to an FTP/FTPS Server

Define a function to upload files to FTP/FTPS in Node.js with `basic-ftp` as below:

```javascript
const ftp = require("basic-ftp") 

async function uploadFileToFTP(localFile, remotePath) {
    const client = new ftp.Client()
    
    try {
        await client.access({
            host: "<YOUR_FTP_HOST>",
            user: "<YOUR_FTP_USER_USERNAME>",
            password: "<YOUR_FTP_USER_PASSWORD>",
            secure: false
        })
        
        // upload the local file located in localFile
        // to remotePath
        await client.uploadFrom(localFile, remotePath)
    }
    catch(err) {
        console.log(err)
    }
    client.close()
}

// upload the local file "report.xlxs" to
// the remote path "reports/report.xlsx"
uploadFileToFTP("report.xlsx", "reports/report.xlsx")
```

`uploadFrom()` will upload data from a readable stream or local file to a remote file via FTP or FTPS. In particular, `localFile` can be a [`Readable`](https://nodejs.org/api/stream.html#class-streamreadable) [Node.js stream](https://nodejs.org/api/stream.html#class-streamreadable) or a string with the complete local path of the local file.

Note that if the remote file already exists, it will be overwritten.

## SFTP in Node.js

[`ssh2-sftp-client`](https://www.npmjs.com/package/ssh2-sftp-client) is a Promise-based SFTP client library for Node.js. Keep in mind that you cannot use it to connect to an FTP/FTPS server. Let's now see how to use `ssh2-sftp-client`to connect to an SFTP server using Node.js.

First, add `ssh2-sftp-client` to your project's dependencies with:npm i ssh2-sftp-client

Then, you can then use it to connect to SFTP as follows:

```javascript
// import ssh2-sftp-client
const SFTPClient = require("ssh2-sftp-client") 
// ESM: import SFTPClient from "ssh2-sftp-client"

async function operationWithSFTP() {
    // initialize the SFTP client
    const sftp = new SFTPClient()
    
    try {
        // connect to the FTP/FTPS server
        await sftp.connect({
            host: "<YOUR_SFTP_HOST>",
            username: "<YOUR_SFTP_USER_USERNAME>",
            password: "<YOUR_FTP_USER_PASSWORD>",
        })
        
        // perform operations on the SFTP server...
    } catch(e) {
        console.log(e)
    }
    
    // close the client connection
    await sftp.close()
}
```

Do not forget to replace the placeholder strings with your SFTP credentials.

It's time to learn how to upload and download a file via SFTP with `ssh2-sftp-client`!

### Download a File From an SFTP Server

You can define a function to download a file from an SFTP server with Node.js through `ssh2-sftp-client` as below:

```javascript
const SFTPClient = require("ssh2-sftp-client") 

async function downloadFileFromSFTP(localFile, remotePath) {
    const sftp = new SFTPClient()
    
    try {
        await sftp.connect({
            host: "<YOUR_SFTP_HOST>",
            username: "<YOUR_SFTP_USER_USERNAME>",
            password: "<YOUR_FTP_USER_PASSWORD>",
        })

        // download the file located in remotePath
        // to localFile
        await sftp.get(remoteFile, localFile);        
    } catch(e) {
        console.log(e)
    }
    
    // close the client connection
    await sftp.close()
}

// download the remote file "marketing/CSV/prices.csv"
// and save it to the local file "prices.csv"
downloadFileFromSFTP("prices.csv", "marketing/CSV/prices.csv")
```

[`get()`](https://github.com/theophilusx/ssh2-sftp-client#getpath-dst-options--stringstreambuffer) will download a remote file from an SFTP server and pipe its data to a buffer, writable stream, or local file. Specifically, `localFile` can be a [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer), a `Writable` stream, or a string with the complete local path of where to save the file downloaded via SFTP.

### Upload a File to an SFTP Server

Create a function to upload a file to SFTP in Node.js with `basic-ftp` as below:

```javascript
const SFTPClient = require("ssh2-sftp-client") 

async function uploadFileToSFTP(localFile, remotePath) {
    const sftp = new SFTPClient()
    
    try {
        await sftp.connect({
            host: "<YOUR_SFTP_HOST>",
            username: "<YOUR_SFTP_USER_USERNAME>",
            password: "<YOUR_FTP_USER_PASSWORD>",
        })

        // upload the file located in localFile
        // to remoteFile
        await sftp.put(localFile, remoteFile);        
    } catch(e) {
        console.log(e)
    }
    
    // close the client connection
    await sftp.close()
}

// upload the local file "data.xslx"
// to store it to the remote file "marketing/Excel/data.xlsx"
uploadFileToSFTP("data.xslx", "marketing/Excel/data.xlsx")
```

[`put()`](https://github.com/theophilusx/ssh2-sftp-client#putsrc-remotepath-options--string) will upload data from a buffer, readable stream, or local file to a remote file via SFTP. In detail, `localFile` can be a `Buffer`, `Readable` stream or a string containing the complete local path of the local file.

## Conclusion

In this article, you learned the difference between FTP, FTPS, and SFTP, and how to upload and download a file in each of those protocols. Specifically, you learned how to use `basic-ftp` to deal with an FTP/FTPS server. Similarly, you saw how to use the `ssh2-sftp-client` Node.js library to deal with an SFTP server. You know now how to upload and download files via FTP, FTPS, and SFTP in Node.js.

Thanks for reading! I hope you found this article helpful.
  
***
_The post "[How To Upload and Download a File With FTP/FTPS/SFTP in Node.js](https://writech.run/blog/how-to-upload-and-download-a-file-with-ftp-ftps-sftp-in-node-js-b50e196841f1/)" appeared first on [Writech](https://writech.run)._