DEV Community

Cover image for How To Upload and Download a File With FTP/FTPS/SFTP in Node.js
Antonello Zanini for Writech

Posted on • Edited on

How To Upload and Download a File With FTP/FTPS/SFTP in Node.js

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), FTPS (FTP Secure), and SFTP (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 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. As stated on the official GitHub page of the project, 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:

// 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()
}
Enter fullscreen mode Exit fullscreen mode

Be sure to replace the placeholder strings with your FTP credentials. Also, note that basic-ftp is a Promise-based library. For this reason, its functions should be called with the await keyword and in an async function. Find out more about how to use Promises with async/await in JavaScript.

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:

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")
Enter fullscreen mode Exit fullscreen mode

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 Node.js stream 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:

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")
Enter fullscreen mode Exit fullscreen mode

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 Node.js stream 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 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-clientto 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:

// 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()
}
Enter fullscreen mode Exit fullscreen mode

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:

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")
Enter fullscreen mode Exit fullscreen mode

get() 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, 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:

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")
Enter fullscreen mode Exit fullscreen mode

put() 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" appeared first on Writech.

Top comments (0)