Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Node.JS ftp-promise how to always wait finish download before showing the values

gahhon

New Coder
index.js
JavaScript:
const Utils= require('./utils');

async function callFTP() {
    const responseFTP = await Utils.FtpAPI('url', 'username', 'password', '202211070859.xml')
    console.log('index: ', responseFTP);
}

callFTP();

utils.js
JavaScript:
const convert = require('xml-js');
const moment = require('moment');
var PromiseFtp = require('promise-ftp');
const fs = require('fs');

async function FtpAPI(ftpURL, ftpUserName, ftpPassword, ftpLastFileRead) {
    //Initialize Promise FTP Connection
    const promiseFtp = new PromiseFtp();
    const remoteFilePath = '/BR/AGIN/20221107';
    const localTempPath = './public/temp/';
    const connectionProp = {
        host: ftpURL,
        user: ftpUserName,
        password: ftpPassword
    };

    return new Promise((resolve, reject) => {
        promiseFtp.connect(connectionProp).then(() => {
            return promiseFtp.list(remoteFilePath);
        }).then((data) => {
            let filteredFile = [];

            //Filter out already read files
            if (ftpLastFileRead != null) {
                let tempList = data.filter((element) => {
                    return element.name > ftpLastFileRead;
                });

                //Store into filteredFile Object
                tempList.forEach((fileElement) => {
                    filteredFile.push({
                        fileName: fileElement.name,
                        fileDate: fileElement.date
                    });
                });
            } else {
                data.forEach((fileElement) => {
                    filteredFile.push({
                        fileName: fileElement.name,
                        fileDate: fileElement.date
                    });
                });
            }

            // //filteredFile Iteration to download files to local repository
            filteredFile.forEach((listFile) => {
                promiseFtp.get(`${remoteFilePath}/${listFile.fileName}`).then((stream) => {
                    stream.pipe(fs.createWriteStream(localTempPath + listFile.fileName));
                    console.log(`[game-utils.js] ### ${localTempPath}${listFile.fileName} FTP-API is Downloaded`);
                });
            });

            resolve(filteredFile); //Trying to return JSON Array after downloaded
        }).then(() => {
            promiseFtp.end();
        }).catch((error) => {
            promiseFtp.end();
            console.log('Exception / Error: ' + error);
            reject(error);
        })
    });
}

module.exports = {
    FtpAPI
};

Result
201745136-7cde8643-37b1-44ef-bc5e-909081366346.png

Problem:-
How can I return the filteredFile to index.js after download complete for each file or how to know when the downloading is totally complete?
I dig and tried a lot of google research, non-of them working for my current situation tho.
 
It resolved by sending back the resolve with value when last index of the forEach loop.

JavaScript:
//filteredFile Iteration to download files to local repository
filteredFile.forEach((listFile, idx, array) => {
    promiseFtp.get(`${remoteFilePath}/${listFile.fileName}`).then((stream) => {
        stream.pipe(fs.createWriteStream(localTempPath + listFile.fileName));
        console.log(`[game-utils.js] ### ${localTempPath}${listFile.fileName} FTP-API is Downloaded`);
    }).catch((error) => {
        promiseFtp.end();
        reject(error);
    });
    
    if (idx === array.length - 1) {
        //Send back filteredFile JSON Array once last read
        resolve(filteredFile);
    }
});
 
Back
Top Bottom