【问题标题】:How to create a file in the cloud function and upload to a bucket如何在云函数中创建文件并上传到bucket
【发布时间】:2020-09-26 22:22:37
【问题描述】:

一段时间以来,我一直在尝试创建一个包含一些文本(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) 

【问题讨论】:

标签: javascript node.js firebase google-cloud-functions google-cloud-storage


【解决方案1】:

您没有正确使用fs.writeFile()。从链接文档中可以看出,它需要 3 或 4 个参数,其中一个是回调。错误消息是说您没有通过回调。最重要的是,它不返回一个承诺,所以你不能有效地等待它。考虑使用fs.writeFileSync() 来简化此操作。

【讨论】:

    猜你喜欢
    • 2023-03-17
    • 2021-10-29
    • 2022-01-28
    • 1970-01-01
    • 2016-12-23
    • 2017-12-12
    • 2021-03-30
    • 2015-05-13
    • 1970-01-01
    相关资源
    最近更新 更多