我试图通过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');
}
使用更高范围的变量:
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)
}