【问题标题】:Uploading data from firebase functions to firebase storage?将数据从firebase函数上传到firebase存储?
【发布时间】:2020-02-14 02:06:32
【问题描述】:

我有一个使用 node.js 运行的网站,后端在 Firebase Functions 上运行。我想将一堆 JSON 存储到 Firebase 存储。当我在 localhost 上运行时,下面的 sn-p 工作得很好,但是当我将它上传到 Firebase 函数时,它显示Error: EROFS: read-only file system, open 'export-stock-trades.json。有谁知道如何解决这个问题?

    fs.writeFile(fileNameToReadWrite, JSON.stringify(jsonObjToUploadAsFile), function(err){
        bucket.upload(fileNameToReadWrite, {
            destination: destinationPath,
        });

        res.send({success: true});
    });

【问题讨论】:

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


    【解决方案1】:

    我无法确定,因为您的函数的大部分上下文都丢失了,但看起来您的函数正在尝试先将文件写入本地磁盘 (fs.writeFile),然后上传 (@987654324 @)。

    在 Cloud Functions 上,您编写的代码仅对 /tmp 具有写入权限, 这是节点中的os.tmpdir()。在 documentation:

    文件系统唯一可写的部分是 /tmp 目录,它 您可以使用将临时文件存储在函数实例中。这是一个 本地磁盘挂载点,称为“tmpfs”卷,其中写入数据 到卷存储在内存中。注意会消耗内存 为该功能提供的资源。

    这可能是导致您的代码失败的原因。

    顺便说一句,如果您要上传的数据在内存中,您不必像现在这样先将其写入文件。你可以改用file.save()

    【讨论】:

      【解决方案2】:

      我觉得这可行的另一种方法是将 JSON 文件转换为缓冲区,然后执行这样的操作(下面的代码 sn-p)。我写了一篇关于如何使用 Google Cloud Storage 做到这一点的文章,但它与 Firebase 存储配合得很好。您唯一需要更改的是“service-account-key.json”文件。

      文章的链接可以在这里找到:Link to article on medium

      const util = require('util')
      const gc = require('./config/')
      const bucket = gc.bucket('all-mighti') // should be your bucket name
      
      /**
       *
       * @param { File } object file object that will be uploaded
       * @description - This function does the following
       * - It uploads a file to the image bucket on Google Cloud
       * - It accepts an object as an argument with the
       *   "originalname" and "buffer" as keys
       */
      
      export const uploadImage = (file) => new Promise((resolve, reject) => {
        const { originalname, buffer } = file
      
        const blob = bucket.file(originalname.replace(/ /g, "_"))
        const blobStream = blob.createWriteStream({
          resumable: false
        })
        blobStream.on('finish', () => {
          const publicUrl = format(
            `https://storage.googleapis.com/${bucket.name}/${blob.name}`
          )
          resolve(publicUrl)
        })
        .on('error', () => {
          reject(`Unable to upload image, something went wrong`)
        })
        .end(buffer)
      })
      

      【讨论】:

        猜你喜欢
        • 2021-03-30
        • 2021-04-10
        • 1970-01-01
        • 1970-01-01
        • 2020-11-17
        • 1970-01-01
        • 2017-10-19
        • 2019-08-29
        • 2019-12-20
        相关资源
        最近更新 更多