【问题标题】:Firebase function: Error: unable to open for writeFirebase 功能:错误:无法打开写入
【发布时间】:2022-02-01 20:43:36
【问题描述】:

所以我试图实现一个 firebase 功能。我去了firebase函数存储库示例并复制了它。一切正常“部署完成!”没有错误的迹象。但是,当我尝试将图像上传到 firebase 商店时,firebase 功能无法打开它?

有一个我用过的代码:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp()
const {Storage} = require("@google-cloud/storage");
const gcs = new Storage();
const path = require('path');
const os = require('os');
const fs = require('fs');
const sharp = require("sharp");

exports.generateThumbnail = functions.storage.object().onFinalize(async (object) => {

  const fileBucket = object.bucket; // The Storage bucket that contains the file.
  const filePath = object.name; // File path in the bucket.
  const contentType = object.contentType; // File content type.
  const metageneration = object.metageneration; // Number of times metadata has been generated. New objects have a value of 1.

  if (!contentType.startsWith('image/')) {
    return console.log('This is not an image.');
  }

  const fileName = path.basename(filePath);

  if (fileName.startsWith('thumb_')) {
    return console.log('Already a Thumbnail.');
  }

  const bucket = admin.storage().bucket(fileBucket);
  const tempFilePath = path.join(os.tmpdir(), fileName);
  console.log('Created temporary path',tempFilePath);
  const metadata = {
    contentType: contentType,
  };
  await bucket.file(filePath).download({destination: tempFilePath});
  console.log('Image downloaded locally to', tempFilePath);

  const thumbFileName = `thumb_${fileName}`;
  const thumbFilePath = path.join(path.dirname(filePath), thumbFileName);
  console.log('Created thumb path',tempFilePath);
  const size = 200;

  /*await*/ sharp(tempFilePath).resize(size,size).toFile(thumbFilePath);

  await bucket.upload(tempFilePath, {
    destination: filePath,
    metadata: metadata,
  });
  
  return fs.unlinkSync(tempFilePath);
});

错误:

【问题讨论】:

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


    【解决方案1】:

    Cloud Functions 具有只读文件系统,/tmp 目录除外。您必须确保将数据写入路径/tmp/your-file

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

    Cloud Functions Execution Environment

    【讨论】:

      【解决方案2】:

      我想这也适用于 Firebase,否则请发表评论:

      gcsfs

      如果将gcsfs放在“requirements.txt”中,并在Python代码中导入gcsfs,就可以这样使用模块(以Have a look at an example for saving a csv为例:

      fs = gcsfs.GCSFileSystem(project=MY_PROJECT)
      fs.ls(BUCKET_NAME)
      # or choose 'w' here:
      with fs.open(filepath, 'wb') as outcsv:
          ...
      

      更多链接:

      【讨论】:

        猜你喜欢
        • 2019-12-23
        • 1970-01-01
        • 2019-09-25
        • 2021-08-24
        • 1970-01-01
        • 2011-12-07
        • 1970-01-01
        • 2012-08-20
        • 2021-03-05
        相关资源
        最近更新 更多