【问题标题】:How to delete a file using cloud function JavaScript firebase?如何使用云功能 JavaScript firebase 删除文件?
【发布时间】:2020-04-29 19:06:06
【问题描述】:

当从实时数据库中删除数据节点时,我想从存储中删除文件。要删除的文件的名称是在删除之前取的。文件名保存在名为“imageTitle”的子节点中。该代码在实现文件删除代码之前运行良好。我的意思是节点被完全删除了。

当我实现文件删除代码时,其余部分不起作用,但没有任何错误。文件删除后的代码不起作用。我不知道为什么。

这是一个学术期末项目。

bucket 中有一个名为 images 的文件夹,我需要删除的文件就在里面。文件名取自要在名为 imageTitle 的实时数据库中删除的节点中的子节点:

    'use strict';

    const functions = require('firebase-functions');
    const admin = require('firebase-admin');
    admin.initializeApp();


    exports.changetime = functions.database.ref('/posts/{pushId}')
    .onCreate((snapshot, context) => {
    const editDate = Date.now()
    datas = snapshot.val();
    return snapshot.ref.update({editDate})
})

    const CUT_OFF_TIME = 1 * 60 * 1000; 

/**
 * This database triggered function will check for child nodes that are older than the
 * cut-off time. Each child needs to have a `timestamp` attribute.
 */


    exports.deleteOldItems = functions.database.ref('/posts/{pushId}').onWrite(async (change, 
    context) => {
    const ref = change.after.ref.parent; // reference to the parent
    const now = Date.now();
    const id = context.params.pushId;
    const cutoff = now - CUT_OFF_TIME;
    const oldItemsQuery = ref.orderByChild('createdDate').endAt(cutoff);
    const snapshot = await oldItemsQuery.once('value');

    const getImageTitle = admin.database().ref(`/posts/${id}/imageTitle`).once('value');

    return getImageTitle.then(imageTitle => {

    console.log('post author id', imageTitle.val());
    const imageName =  imageTitle.val();
    const filePath = 'images/' + imageName;


    const path = `images/${imageName}`;
    const bucket = app.storage().bucket();
    return bucket.file(path).delete().then(() =>{
    console.log(`File deleted successfully in path: ${imageName}`)

/* The problem is here. the code doesn't work after file.delete function. no errors. but doesn't work
if I remove that piece of code the other codes work fine. I mean the realtime database nodes get deleted and updated perfectly */

    const updates = {};
    snapshot.forEach(child => {
    updates[child.key] = null;
    if(updates[child.key] == null){
    admin.database().ref(/post-likes/+id).remove();
   }
   })

   return ref.update(updates);
   });
   });
   [my storage looks like this][1]});

bucket 中有一个名为 images 的文件夹,我需要删除的文件就在里面。文件名取自实时数据库中要删除的节点中的子节点imageTitle:

enter image description here

【问题讨论】:

  • 您似乎在此代码的引用中缺少路径周围的引号:admin.database().ref(/post-likes/+id).remove() 不确定这是否是您唯一的问题。在我的手机上执行此操作。
  • 那部分代码工作正常。问题在于文件删除。我只是不知道如何实现它

标签: javascript firebase firebase-realtime-database google-cloud-functions


【解决方案1】:

我认为这是问题所在:

const filePath = 'images/' + imageName;


const path = `images/${imageName}`;

您应该在存储桶引用中使用 filePath 而不是 pathconst path = `images/${imageName}`; 是查询时使用的通配符语法,而不是分配变量时使用....认为您在这里停留在“飞镖”模式:-)。因此,不确定 path 包含什么,但可以通过 console.log 来查看。

这是我用来从存储桶中删除图像的一些代码,效果很好。首先,需要检查几件事(最好使用 console.log 完成,永远不要假设您知道变量中的内容),然后执行以下操作:

  1. 确保imageNamefilePathpathbucket 包含它们应包含的内容。
  2. 在您的代码中包含 .catch 块以检查是否确实存在错误
  3. 我不清楚console.log(`File deleted successfully in path: ${imageName}`) 是否正在执行,但如果不是,那么您的 file.delete 肯定会抛出 catch 块应该捕获的错误。

代码sn-p:

const oldProfileImagePath = "profileImages/" + authenticatedUserId + "/" + oldProfileImageName;
      return bucket.file(oldProfileImagePath).delete()
        .then(function () {
          console.info("Old Profile Image: " + oldProfileImagePath + " deleted!");
        })
        .catch(function (error) {
          console.error("Remove Old Profile Image: " + oldProfileImagePath +
            " failed with " + error.message)
        });

【讨论】:

  • 感谢@GrahamD。 thnx 帮助我解决了这个问题。你提到的也是问题所在。并且返回承诺还有另一个问题。
  • const updates = {}; snapshot.forEach(child => { updates[child.key] = null; admin.database().ref(/post-likes/+id).remove(); const promises = []; promises.push(ref.update(updates)); const bucket = admin.storage().bucket(); promises.push(bucket.file(filePath).delete()); }) // execute all updates in one go and return the result to end the function return Promise.all(promises);
  • 欢迎您。很高兴我能帮助你。没有发现退货问题。如果愿意,也请对答案进行投票,给我更多的声望点,让我保持动力。谢谢。 :-)
猜你喜欢
  • 1970-01-01
  • 2020-10-10
  • 1970-01-01
  • 1970-01-01
  • 2020-03-28
  • 2021-01-23
  • 1970-01-01
  • 1970-01-01
  • 2020-09-08
相关资源
最近更新 更多