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:
- Install Python
- Install lftp (link)
- Install Node.js
- Install Node.js development component through Visual Studio Installer
After these installations, start Visual Studio to create a project and add JS code:
- In Visual Studio, go to “File > New > Project”
- Select “Blank Node.js Console Application” project type
- Click “Next”, give a name, and click “Create”
Once the project is created, you will need to install ftps package through npm:
- Go to the Solution Explorer (on the right side of the Visual Studio window)
- Find “npm” (under the project name)
- Right click on “npm” and select “Install New npm Packages”
- Search for “ftps”
- Select the first result. Click “Install Package”. This package uses lftp and supports FTP, FTPS, and SFTP
- The window may not react. Wait a few seconds. Then close the window
- Refresh the Solution Explorer
- 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:
- FTP server address
- FTP username
- FTP password
- Protocol (Possible values: ‘ftp’, ‘sftp’, ‘ftps’)
- Port (If it’s your server requires a port other than 22)
- FTP command (The example adds a file called text.txt to the FTP folder. This file should exist in your Visual Studio project folder)
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