首页 > 解决方案 > 如何在云函数中创建文件并上传到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) 

标签: javascriptnode.jsfirebasegoogle-cloud-functionsgoogle-cloud-storage

解决方案


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


推荐阅读