我正在尝试读取Firebase函数中的csv文件,以便可以将邮件发送到所有记录。我打算按照以下步骤进行操作
下面是函数
import * as functions from "firebase-functions";
import * as mkdirp from "mkdirp-promise";
import * as os from "os";
import * as path from "path";
import csv = require('csvtojson');
const gcs = require('@google-cloud/storage')({ keyFilename: 'service-account-credentials.json' });
const csvDirectory = "csv";
export = functions.storage.object().onFinalize(async (object) => {
const filePath = object.name;
const contentType = object.contentType;
const fileDir = path.dirname(filePath);
if(fileDir.startsWith(csvDirectory) && contentType.startsWith("text/csv")) {
const bucket = gcs.bucket(object.bucket);
const file = bucket.file(filePath);
const fileName = path.basename(filePath);
const tempLocalFile = path.join(os.tmpdir(), filePath);
const tempLocalDir = path.dirname(tempLocalFile);
console.log("values", bucket, file, fileName, tempLocalDir, tempLocalFile);
console.log("csv file uploadedeeeed");
await mkdirp(tempLocalDir);
await bucket.file(filePath).download({
destination: tempLocalFile
});
console.log('The file has been downloaded to', tempLocalFile);
csv()
.fromFile(tempLocalFile)
.then((jsonObj) => {
console.log(jsonObj);
})
}
});
运行代码时,我只上传了我已在console.log内编写的csv文件,然后在1分钟后超时。我也没有得到该文件已下载到log。任何人都可以看一下代码,并帮助我摆脱困境。
答案 0 :(得分:0)
您正在混用async/await
和对方法的调用。您还应该then()
。
以下应该可以解决这个问题(未测试):
export = functions.storage.object().onFinalize(async (object) => {
const filePath = object.name;
const contentType = object.contentType;
const fileDir = path.dirname(filePath);
try {
if (fileDir.startsWith(csvDirectory) && contentType.startsWith("text/csv")) {
//.....
await mkdirp(tempLocalDir);
await bucket.file(filePath).download({
destination: tempLocalFile
});
console.log('The file has been downloaded to', tempLocalFile);
const jsonObj = await csv().fromFile(tempLocalFile);
console.log(jsonObj);
return null;
} else {
//E.g. throw an error
}
} catch (error) {
//.....
}
});
还要注意(与async/await
和then()
的混合使用无关),并且在代码中包含以下行
csv().fromFile(tempLocalFile).then(...)
您没有返回fromFile()
方法返回的Promise。这是Cloud Functions中的关键点。
我建议您观看有关Cloud Functions(use await
for the fromFile()
method)的官方视频系列,尤其是Promises上名为“ Learn JavaScript Promises”的视频。