javascript - 如何在云函数中创建文件并上传到bucket
问题描述
一段时间以来,我一直在尝试创建一个包含一些文本(hello world)的文件(sample.txt),最后将其上传到存储桶中。有没有办法我可以实现这个?我尝试的代码如下:
exports.uploadFile = functions.https.onCall(async (data, context) => {
try {
const tempFilePath = path.join(os.tmpdir(), "sample.txt");
await fs.writeFile(tempFilePath, "hello world");
const bucket = await admin.storage().bucket("allcollection");
await bucket.upload(tempFilePath);
return fs.unlinkSync(tempFilePath);
} catch (error) {
console.log(error);
throw new functions.https.HttpsError(error);
}
});
每当运行此代码时,我都会在 firebase 控制台中得到类似这样的错误:
TypeError [ERR_INVALID_CALLBACK]: Callback must be a function
at maybeCallback (fs.js:128:9)
at Object.writeFile (fs.js:1163:14)
解决方案
您没有正确使用fs.writeFile()。从链接文档中可以看出,它需要 3 或 4 个参数,其中一个是回调。错误消息是说您没有通过回调。最重要的是,它不返回一个承诺,所以你不能有效地等待它。考虑使用fs.writeFileSync()来简化此操作。
推荐阅读
- php - Laravel/Lumen Auth JWT 令牌在后续请求中无效,它可能已过期吗?
- javascript - 聚合物 CLI 和要求
- python - 如何使用 python 和正则表达式合并两个文本文件
- firebase - Firebase cloud firestore:如何防止流氓字段?
- javascript - 如何在Angular中单击按钮时将嵌套滚动条向下滚动到嵌套滚动div的底部
- html - 为什么我的 CSS 没有在实时服务器上添加我今天添加的内容?
- android - 找不到 com.google.android.gms.internal.zzbfm 无法访问 zzbfm 类文件
- c# - 有没有办法关闭 Hangfire 对 serilog 所做的日志记录?
- php - 使用 RDKAFKA 将多个组 id 分配给多个消费者
- c# - 如何处理动态复选框asp.net mvc 5