繁体   English   中英

从firebase函数上传数据到firebase存储?

[英]Uploading data from firebase functions to firebase storage?

我有一个运行 node.js 的网站,后端运行 Firebase 功能。 我想存储一堆 JSON 到 Firebase 存储。 当我在本地主机上运行时,下面的代码片段工作得很好,但是当我将它上传到 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});
    });

我不能确定,因为你的 function 的大部分上下文都丢失了,但看起来你 function 正在尝试先将文件写入本地磁盘( fs.writeFile ),然后上传它( bucket.upload )。

在 Cloud Functions 上,您编写的代码只有对 /tmp 的写入权限,即 node.js 中的os.tmpdir() 文档中阅读更多相关信息:

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

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

顺便说一句,如果你要上传的数据在memory,你不必像现在这样先把它写入文件。 您可以改为使用file.save()

我认为这可行的另一种方法是将 JSON 文件转换为缓冲区,然后执行这样的操作(下面的代码片段)。 我写了一篇关于如何使用 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)
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM