通过FTP在Node和AWS Lambda中使用Async&Promises下载txt文件

时间:2019-02-18 20:39:55

标签: javascript node.js amazon-web-services async-await aws-lambda

我正在使用单个Node模块basic-ftp在AWS Lambda中下载一个txt文件,并将其放在Lambda函数内的/ tmp /目录中。

然后我想在ftp功能之外使用txt文件及其内容。

我正在使用Async和Promises,并且对代码有些迷惑。 AWS Lambda中返回的当前错误是

module initialization error: ReferenceError
      await finalData = (() => {
      ^^^^^^^^^^^^^^^

此行await finalData = (() => {

的结果

有人可以帮助解决此问题,并帮助我在FTP功能之外访问finalData吗?

var fs = require('fs');
var ftp = require("basic-ftp");
var path = require('path');

exports.handler = async (event, context, callback) => {

var fullPath = event.line_items[0].meta_data[2].value.tmp_name; // File path on Linux server -------
var myFileNameWithExtension = path.basename(fullPath); // Uploaded filename with the file extension eg. filename.txt

// FTP Function - Download from FTP and write to /tmp/ within AWS Lambda function
example()
//example().then(finalData=> callback(finalData))

async function example() {
    var finalData = '';

    const client = new ftp.Client()
    client.ftp.verbose = true
    try {
    await client.access({
        host: "XXXX",
        user: "XXXX",
        password: "XXXX",
    })

    let writeStream = fs.createWriteStream('/tmp/' + myFileNameWithExtension);
    await client.download(writeStream, myFileNameWithExtension)

    await finalData = (() => {
        return new Promise((resolve, reject) => {

        writeStream
            .on('finish', () => {
            fs.readFile("/tmp/" + myFileNameWithExtension, function (err, data) {
                if (err) {
                reject(err)
                } else {
                console.log('Contents of AWS Lambda /tmp/ directory', data);
                resolve(data);
                }
            });
            })
            .on('error', (err) => {
            console.log(err);
            reject(err);
            })
        })
    })();
    }
    catch (err) {
    console.log(err)
    }
    client.close();
    return finalData;
}

// Output contents of downloaded txt file into console and use in later code outside of the FTP function
console.log("Raw text:\n" + finalData.Body.toString('ascii'));

};

1 个答案:

答案 0 :(得分:0)

finalData仅在返回它的示例中定义,但是您没有将其分配给任何东西。结合Luca Kiebel的评论,尝试添加

const finalData = await example();

然后注销。

由于finalData是在函数示例中定义的,因此仅在该函数以及该函数中定义的任何函数中可用。

You Don't Know JS比我更好地解释了这一点