Site icon port135.com

Code Example to Connect FTP and SFTP using lftp module in Node.js

If you want to access your FTP files through a programmatic way instead of using FTP clients, this Node.js example using lftp will come in handy.

In another post, I explained how to connect FTP using C#: How to upload a file via FTP in C#. In this post, I will share the steps to establish FTP connection using lftp and Node.js.

Steps to connect FTP/SFTP using lftp module with Node.js

Here are the high-level steps for busy developers:

  1. Install Python
  2. Install lftp (link)
  3. Install Node.js
  4. Install Node.js development component through Visual Studio Installer

After these installations, start Visual Studio to create a project and add JS code:

  1. In Visual Studio, go to “File > New > Project”
  2. Select “Blank Node.js Console Application” project type
  3. Click “Next”, give a name, and click “Create”

Once the project is created, you will need to install ftps package through npm:

  1. Go to the Solution Explorer (on the right side of the Visual Studio window)
  2. Find “npm” (under the project name)
  3. Right click on “npm” and select “Install New npm Packages”
  4. Search for “ftps”
  5. Select the first result. Click “Install Package”. This package uses lftp and supports FTP, FTPS, and SFTP
  6. The window may not react. Wait a few seconds. Then close the window
  7. Refresh the Solution Explorer
  8. Expand “npm” to check if “ftps” is installed

Once the package is installed, you are ready to add the code. Go to app.js file and add the code below.

var FTPS = require('ftps');

var ftps = new FTPS({
    host: 'ftp.youraddress,com',
    username: 'username',
    password: 'password',
    protocol: 'sftp',
    port: 22,
    escape: true,
    retries: 0,
    timeout: 100,
    retryInterval: 5,
    retryMultiplier: 1,
    requiresPassword: true,
    autoConfirm: true,
    //cwd: '', 
    //additionalLftpCommands: '',
    //requireSSHKey:  true, 
    //sshKeyPath: '/home1/phrasee/id_dsa', 
    //sshKeyOptions: '' 
});

ftps.addFile('./test.txt').exec(console.log);

Change the following values in this code:

For more parameter options and FTP commands, check this page out.

If you come across “530 User Cannot Log in” message, this post may help: 530 User cannot log in, home directory inaccessible

For “550 Supply Message Incomplete” error, check this post out: 550 supply message incomplete, signature was not verified

Exit mobile version