I am encountering an issue with a Node.js script that uses the ftp library to upload a file to an FTP server. The script should close the connection and terminate once the file upload reaches 100%, but it's not happening as expected. Below is the relevant portion of my code where I believe the issue might be occurring:
async function uploadToFTP() {
const client = new ftp.Client();
client.ftp.verbose = false;
try {
console.log("Connecting to FTP...");
await client.access({
host: process.env.FTP_HOST,
user: process.env.FTP_USER,
password: process.env.FTP_PASSWORD,
secure: process.env.FTP_SECURE === "true",
});
console.log("Connected to FTP.");
const remoteDir = process.env.REMOTE_DIR || "/DataBackup";
console.log(`Ensuring directory ${remoteDir} exists on FTP...`);
await client.ensureDir(remoteDir);
await client.clearWorkingDir();
const fileSize = fs.statSync(zipPath).size;
const uploadBar = new ProgressBar("Uploading [:bar] :percent :etas", {
complete: "=",
incomplete: " ",
width: 40,
total: fileSize,
});
client.trackProgress((info) => {
uploadBar.tick(info.bytes);
});
console.log(`Starting upload of ${zipPath} to FTP...`);
await client.uploadFrom(zipPath, path.basename(zipPath));
console.log("Upload completed.");
} catch (err) {
console.error("Failed to upload zip to FTP server:", err);
} finally {
console.log("Closing FTP connection...");
client.trackProgress(() => {});
try {
await client.close();
console.log("FTP connection closed.");
} catch (closeError) {
console.error("Error closing FTP connection:", closeError);
}
console.log("uploadToFTP completed.");
}
}
The uploadFrom method is used to upload the file, and I'm using client.trackProgress to update a progress bar which indicates the upload progress. The promise returned by uploadFrom should resolve after the file is fully uploaded, allowing the script to proceed to log "Upload completed" and then close the connection.
However, even after the progress bar hits 100% and "Upload completed" is logged, the script does not terminate as it should, indicating that the connection might not be closing properly.