使用createWriteStream

时间:2019-02-15 15:44:19

标签: javascript node.js ftp aws-lambda fs

我试图通过FTP下载.txt文件,然后将此文件分配给一个变量,以后可以在代码中编辑文本。

当从Node.js中的createWriteStream创建变量时,不确定如何设置可在FTP代码块之外使用的变量。

如何将这个.txt传递到变量ftpItem中,然后在FTP函数之外进行访问?

AWS Lambda返回的错误为ftpItem is not defined-总而言之,我正在尝试通过FTP下载TXT文件。将其放在AWS Lambda函数的/ tmp /目录中,然后稍后在代码中打开并编辑该文本。

var fullPath = event.line_items[0].meta_data[2].value.tmp_name; 
const extension = path.extname(fullPath); 
const FileName = path.basename(fullPath, extension); 
const FileNameWithExtension = path.basename(fullPath); 

...

async function example() {
    const client = new ftp.Client()
    client.ftp.verbose = true
    try {
        await client.access({
            host: process.env.FTP_HOST,
            user: process.env.FTP_USERNAME,
            password: process.env.FTP_PASSWORD,
        })
        console.log(await client.list())
        await client.download(fs.createWriteStream('/tmp/' + FileNameWithExtension), FileNameWithExtension)
        var ftpItem = FileNameWithExtension.Body.toString('ascii');
        console.log(ftpItem);
    }
    catch(err) {
        console.log(err)
    }
    client.close()
}

...

// Use the variable ftpItem outside of the FTP call
// Also tried the following with the same error above
await client.download(fs.createWriteStream('/tmp/' + FileNameWithExtension), FileNameWithExtension)
        {
          var ftpItem = download.Body.toString('ascii');
        }  

1 个答案:

答案 0 :(得分:0)

在更高范围内使用变量:

var fullPath = event.line_items[0].meta_data[2].value.tmp_name; 
const extension = path.extname(fullPath); 
const FileName = path.basename(fullPath, extension); 
const FileNameWithExtension = path.basename(fullPath); 
let ftpItem
...

async function example() {
    const client = new ftp.Client()
    client.ftp.verbose = true
    try {
        await client.access({
            host: process.env.FTP_HOST,
            user: process.env.FTP_USERNAME,
            password: process.env.FTP_PASSWORD,
        })
        console.log(await client.list())
        await client.download(fs.createWriteStream('/tmp/' + FileNameWithExtension), FileNameWithExtension)
        // asign the variable here
        ftpItem = FileNameWithExtension.Body.toString('ascii');
        console.log(ftpItem);
    }
    catch(err) {
        console.log(err)
    }
    client.close()
}

...

// Use the variable ftpItem outside of the FTP call
// Also tried the following with the same error above
await client.download(fs.createWriteStream('/tmp/' + FileNameWithExtension), FileNameWithExtension)
        {
          // Here you can use ftpItem
          console.log(ftpItem)
        }