[FTP/Node js] Failure experience of using npm module 'ftp-client'

使用'ftp-client'的失敗經驗

Liv Huang
2 min readDec 24, 2021

For a easy life, we use npm modules to achieve something we want to realize. The request is to download all files in a specific folder via the FTP connection.

1. Can NOT catch the error

If there is an error, the ftp-client lib will throw an error, but even if I use 'try…catch', I can NOT catch the error and the service stops.

// throw the error from lib
throw new Error('The download destination directory ' + dest + ' does not exist.');

2. The specific folder must exist

When we use the download function of 'ftp-client' to download files, an error will be thrown if the local direction does NOT exist, and the remote direction is the same.

SOLUTION

  • For the local direction, I use the 'fs-extra' module.
const fs = require('fs-extra');// ensure the folder exists, if not, create it.
fs.ensureDirSync(local_dir);
// ensure the folder exists and empty it, if not, create it.
fs.emptyDirSync(local_dir);
  • For the remote direction, I use the 'ftp' module.
const ftp = require('ftp');ftp.list(remote_dir, function (err, list) {
if (err || typeof list === 'undefined' || typeof list[0] === 'undefined') {
// error
}
else
{
// folder exists
}
});

3. Ignore the first file

The ftp-client lib will download files but ignore the first file. It can be fixed by modifying the module lib, but I think this is NOT a good idea.

Wget

For the above reasons , I give up using 'ftp-client' instead of using Linux command 'wget'. In the next story, I will explain how to use 'wget' in my service, including the timeout mechanism.

--

--