读取firebase函数中的CSV文件时遇到一些问题



我正在尝试读取Firebase函数中的csv文件,以便将邮件发送到所有记录。我计划进行以下程序

  1. 上传csv
  2. 在finalize函数上激发a
  3. 阅读文件并发送电子邮件

下面是函数

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分钟后超时。我也没有上传该文件。该文件已下载到日志中。有人能看一下代码,帮我摆脱困境吗。

您将async/await的使用与对then()方法的调用混合在一起。您还应该将await用于fromFile()方法。

以下应该可以做到(未经测试(:

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/awaitthen()的混合使用(,代码中有以下行

csv().fromFile(tempLocalFile).then(...)

您没有返回由fromFile()方法返回的Promise。这是云函数中的一个关键点。

我建议你看官方的云功能系列视频(https://firebase.google.com/docs/functions/video-series/)特别是Promises上题为"学习JavaScript Promises"的视频。

最新更新