我正在尝试通过 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)
}
关于javascript - 使用 createWriteStream 为通过 FTP 下载的 txt 文件分配变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54712680/