简体   繁体   中英

How to download a file through FTP with a firebase function?

QUESTION:

Unfortunately, my function finishes execution within seconds instead of executing in full. This is apparently due to the fact that listeners are declared to stream the data: they are not promises I can await to my knowledge.

How may I have my firebase function execute in full ?


CODE:

exports.fifteenMinutesData = functions
.runWith(runtimeOpts)
.pubsub
.schedule('*/15 * * * *')
.timeZone('Etc/UTC')
.onRun((context) => {
    return (async() => {
        try {

            const Client = require('ftp');
            const c = new Client();
            
            c.connect({
                host: "...",
                user: "..."
            });
            
            c.on('ready', async function () {
                c.get('text.txt', async function (err, stream) {
                    if (err)
                        throw err;
                    var content = '';
                    stream.on('data', function (chunk) {
                        content += chunk.toString();
                    });
                    stream.on('end', function () {
                        (async () => {

                            try {
                                let data = content;

                                //etc....
                            }
                            catch(err) {
                                console.log("ERR: "+err);
                            }
                        })()
                    })
                })
            })
        }
        catch(err) {
            console.log("ERR: "+err)
        }
    })()
});

You will need to promisify the result so the module is aware the value is asynchronous. Currently, your callback is not informing the module of anything so the execution exits immediately, you will want a format like

exports.fifteenMinutesData = functions
.runWith(runtimeOpts)
.pubsub
.schedule('*/15 * * * *')
.timeZone('Etc/UTC')
.onRun((context) => new Promise((resolve, reject) => 
{

});

Where you call resolve(data); for the success path and reject(err); for all error execution paths.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM